Python-从两个列表的元素连接创建多个列表
给我: [c_1',c_2'] 我希望得到: ['a_1','a_2'] ['b_1'、'b_2'] [c_1',c_2'] 有人能指出我代码中的错误吗?谢谢 试试这个:Python-从两个列表的元素连接创建多个列表,python,Python,给我: [c_1',c_2'] 我希望得到: ['a_1','a_2'] ['b_1'、'b_2'] [c_1',c_2'] 有人能指出我代码中的错误吗?谢谢 试试这个: lst1 = ['a', 'b', 'c'] lst2 = ['1', '2'] def comb(lst1, lst2): for i in lst1: new_list = [] for j in lst2: new_list.app
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
def comb(lst1, lst2):
for i in lst1:
new_list = []
for j in lst2:
new_list.append(i + '_' + j)
return new_list
print(comb(lst1, lst2))
new_list
每次执行first for循环时都会变为空。因此,在覆盖该值之前创建另一个列表来存储该值,并返回第二个列表,其中包含new\u list
的所有值
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
def comb(lst1, lst2):
finalList = []
for i in lst1:
new_list = []
for j in lst2:
new_list.append(i + '_' + j)
finalList.append(new_list)
return finalList
print(comb(lst1, lst2))
输出:
res = [[f'{x}_{y}' for y in lst2] for x in lst1]
print(res)
只要看看new_list=[]在哪里。您在每次循环迭代中都从头开始创建它。把它移到前面去拿
如果您只想看到打印的3个元素,请将return更改为print
[['a_1', 'a_2'], ['b_1', 'b_2'], ['c_1', 'c_2']]
试试这个
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
def comb(lst1, lst2):
for i in lst1:
new_list = []
for j in lst2:
new_list.append(i + '_' + j)
print(new_list)
comb(lst1, lst2)
将
new_list
定义移到第一个for循环之外。@PéterLeéh这行不通。它只会创建一个包含所有元素的列表。不像OP预期的那样。很可能这是一个特例:更好的方法是使用列表理解。请参阅deadshot’s。如果用返回替换打印,则只会得到第一个结果。您需要将每个构造的列表添加到另一个列表中,然后返回-请参阅最佳解决方案是由deadshot编写的。带有print的解决方案是状态的唯一直接解决方案。显然,要作为输出获得,
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
new_list = []
for i in lst1:
l1=[]
for j in lst2:
l1.append(i + '_' + j)
new_list.append(l1)
print(new_list)
lst1 = ['a', 'b', 'c']
lst2 = ['1', '2']
for e1 in lst1:
newList = []
for e2 in lst2:
newList.append(e1 + "_" + e2)
print(newList)
Output:
['a_1', 'a_2']
['b_1', 'b_2']
['c_1', 'c_2']