简体   繁体   English

在for循环中追加一个列表?

[英]Appending a list within a for loop?

There are 2 given lists, suppose: 有两个给定的列表,假设:

list1 = ['node1','node2','node3','node4']
list2 = ['goal1','goal2','goal3']

I require a list which returns: 我需要一个返回的列表:

result = [['node1','node2','node3','node4','goal1'],
       ['node1','node2','node3','node4','goal2'],
       ['node1','node2','node3','node4','goal3']]

Here is what I have: 这是我有的:

result = []
for i in range (len(list2)):
    list1.append(list2[i])
    result.append(list1)
    list1.pop()

The problem is, result is not being appended with the desired value. 问题是,结果没有附加所需的值。 It prints, 它打印,

[['node1', 'node2', 'node3', 'node4'],
 ['node1', 'node2', 'node3', 'node4'],
 ['node1', 'node2', 'node3', 'node4']] 

after the for loop is completed. for循环完成后。

What am I doing wrong? 我究竟做错了什么?

You can add list1 each goal to the end to list1 using a list comp: 您可以使用list comp将list1每个目标添加到list1的末尾:

list1 = ['node1', 'node2', 'node3', 'node4']
list2 = ['goal1', 'goal2', 'goal3']
print([list1 + [gl] for gl in list2])

Output: 输出:

[['node1', 'node2', 'node3', 'node4', 'goal1'], 
['node1', 'node2', 'node3', 'node4', 'goal2'], 
['node1', 'node2', 'node3', 'node4', 'goal3']]

What your loop is doing is repeatedly appending the same list object ( list1 ) to result . 你的循环正在做的是重复地将相同的列表对象( list1 )附加到result You can verify that by doing something like list1.append(True) after running the loop and checking result again: 您可以在运行循环并再次检查result后执行类似list1.append(True)来验证:

[['node1', 'node2', 'node3', 'node4', True], 
 ['node1', 'node2', 'node3', 'node4', True], 
 ['node1', 'node2', 'node3', 'node4', True]]

What you want to do is instead make a copy of list1 to append each time, such as: 你要做的就是每次都要复制 list1 ,例如:

for i in range (len(list2)):
    list1.append(list2[i])
    result.append(list(list1))
    list1.pop()

Although I would probably instead make use of list concatenation, which implicitly makes a new list: 虽然我可能会使用列表连接,它隐式地创建一个新列表:

for item in list2:
    result.append(list1 + [item])

You can fix this using extend : 您可以使用extend修复此问题:

>>> for i in range(len(list2)):
    tmp = []
    tmp.extend(list1)
    tmp.append(list2[i])
    all_paths.append(tmp)


>>> all_paths
[['node1', 'node2', 'node3', 'node4', 'goal1'], ['node1', 'node2', 'node3', 'node4', 'goal2'], ['node1', 'node2', 'node3', 'node4', 'goal3']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM