问题描述
我正在处理一项任务,并且部分在那里,但坚持如何将输出作为单个列表与字符串。显然,我正在学习,非常感谢您提供的帮助或建议!
这是评估: 计算他们的笛卡尔积,两个列表的 AxB。每个列表的数字不超过 10 个。
例如,如果用户提供两个输入列表: A = [1,2] B = [3,4]
那么笛卡尔积输出应该是: AxB = [(1,3),(1,4),(2,4)]
这是我目前所写的内容:
import itertools
input_A = []
input_B = []
input_A = input('Enter first 2 - 10 characters: ')
input_B = input('Enter second 2 - 10 characters: ')
for combination in itertools.product(input_A,input_B):
print('AxB = ',[combination])
这是我的输出:
Enter first 2 - 10 characters: 12 #I don't get the the below output when using comma separated items
Enter second 2 - 10 characters: 34
AxB = [('1','3')]
AxB = [('1','4')]
AxB = [('2','3')]
AxB = [('2','4')]
解决方法
这是:
import itertools
input_A = list(map(int,input("Enter multiple numbers for first list separated by commas: ").split(",")))
input_B = list(map(int,input("Enter multiple numbers for second list separated by commas: ").split(",")))
result = list(itertools.product(input_A,input_B))
print(f'A x B = {result}')
#output:
#Enter multiple numbers for first list separated by commas: 3,5,7
#Enter multiple numbers for second list separated by commas: 2,4
#A x B = [(3,2),(3,4),(5,(7,4)]
如果你想在用户输入非数字值时捕获异常并不断提示用户输入正确,你可以这样做:
import itertools
while True:
try:
input_A = list(map(int,")))
input_B = list(map(int,")))
result = list(itertools.product(input_A,input_B))
break
except ValueError:
print("Wrong input. Start over!")
print(f'A x B = {result}')
,
由于您无法使用 itertools
,让我们构建一个函数来计算两个集合 A
和 B
的笛卡尔积。我假设您的脚本的用户输入部分可以正常工作。
我将假设您不会进行任何类型的重复删除(从技术上讲,笛卡尔积是在两个集合或独特对象的集合上执行的,但是由于您重新进行用户输入时,用户可能会给出一个包含重复项的列表,而说明中没有提及有关处理该项的任何内容)。
举个小例子,让 A = {0,1,2}
和 B = {3,4,5}
。那么笛卡尔积是
{(0,3),(0,5),(1,(2,5)}
请注意,从左到右,每个元组的第一个元素似乎并不经常变化。生成此元组列表的系统方法是首先从 A
中取出一个元素并将其“固定”到位,同时从 B
中取出每个元素并将它们配对。所以在伪代码中:
take 0 from A
take 3 from B -> (0,3)
take 4 from B -> (0,4)
take 5 from B -> (0,5)
no more elements in B
take 1 from A
take 3 from B -> (1,3)
take 4 from B -> (1,4)
.
.
.
或者更简洁:for each item in A,pair it with an element from B
。
在 Python 中:
>>> for a in A:
... for b in B:
... print(f"({a},{b})")
...
(0,3)
(0,4)
(0,5)
(1,3)
(1,4)
(1,5)
(2,3)
(2,4)
(2,5)
我会让你把最后一部分放进去(以某种方式得到你的结果,因为这些代码所做的就是在每次迭代中打印 a
和 b
的值)。
所以我想我明白了(只要你不在用户输入中使用逗号或空格!)这将不得不做,教授会标记他不喜欢的东西,所以这是我要做什么...感谢所有提出想法的人,我显然需要离开它一天才能更清楚地看到它。
def cartesian(list_A,list_B):
AxB = [ ]
for A in list_A:
for B in list_B:
AxB.append((A,B))
print('AxB = ',AxB)
list_A = input('Enter up to 10 numbers for List A: ')
list_B = input('Enter up to 10 numbers for List B: ')
cartesian(list_A,list_B)
输出:
Enter up to 10 numbers for List A: 12
Enter up to 10 numbers for List B: 34
AxB = [('1','3'),('1','4'),('2','4')]