我是python的新手,正在尝试通过在列表中附加每个项目来从另外2个列表中创建一个新列表。
for number in num:
for names in name:
print(number+names)
num = [1,2,3,4,5]
name = ['Tom','Bob','Dave']
new_desired_list = [1Tom,1Bob,1Dave,2Tom,2Bob,2Data,3Tom,3Bob,3Dave..etc]
答案 0 :(得分:3)
好像您想要两个列表的笛卡尔积。为此,您拥有itertools.product
。为了加入字符串,您可以使用字符串格式:
from itertools import product
[f'{i}{j}' for i,j in product(num, name)]
# ['{}{}'.format(i,j) for i,j in product(num, name)] # for Python 3.6<
# ['1Tom', '1Bob', '1Dave', '2Tom', '2Bob'...
答案 1 :(得分:1)
您可以尝试添加列表;)
l = []
numbers = [1,2,3,4,5]
names = ['Tom','Bob','Dave']
for number in numbers:
for name in names:
l.append(str(number) + str(name))
print(l)
答案 2 :(得分:0)
使用列表理解:
new_list = [str(i)+x for i in num for x in name]
示例:
>>> num = [1,2,3,4,5]
>>> name = ['Tom','Bob','Dave']
>>>
>>> new_list = [str(i)+x for i in num for x in name]
>>> new_list
['1Tom', '1Bob', '1Dave', '2Tom', '2Bob', '2Dave', '3Tom', '3Bob', '3Dave', '4Tom', '4Bob', '4Dave', '5Tom', '5Bob', '5Dave']
>>>