我一直试图将列表中的每个数字乘以同一列表中的每个数字,并打印每个操作的结果:
list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
应该是
1 * 1
1 * 2
...
...
2 * 1
2 * 2
...
...
3 * 1
3 * 2
依次类推,直到每个数字乘以同一列表中的每个数字。
我知道这是完全错误的,但这是到目前为止我得到的:
def table():
list1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
num = len(list1)
while num >= 1:
for numero in list1:
numero = numero * (num -1)
print(numero)
num = num -1
table()
我该如何实现?
答案 0 :(得分:2)
您也可以尝试使用itertools.product
,就像@ShadowRanger在评论中说的那样:
ls = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
import itertools
product=list(itertools.product(map(int,ls),repeat=2))
for i in product:
print(f'{i[0]}*{i[1]} = {i[0]*i[1]}')
#Try this, in case you only want the result of the product:
#
#product=list(map(lambda x: f'{x[0]*x[1]}\n',product))
#print(*product)
输出:
1*1 = 1
1*2 = 2
1*3 = 3
1*4 = 4
1*5 = 5
1*6 = 6
1*7 = 7
1*8 = 8
1*9 = 9
1*10 = 10
2*1 = 2
2*2 = 4
2*3 = 6
2*4 = 8
2*5 = 10
2*6 = 12
2*7 = 14
2*8 = 16
2*9 = 18
....
答案 1 :(得分:1)
for i in li:
for j in li:
print(f'{i} * {j} = {int(i)*int(j)}')
print('')
我认为这不是有效的方法,但是可以达到您想要的结果。
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
....
答案 2 :(得分:0)
这对我有用:
my_list = list(map(int, ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]))
new_list = [number_n * number_m for number_n in my_list for number_m in my_list]
print(new_list)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]