有两个给定的列表,假设:
list1 = ['node1','node2','node3','node4'] list2 = ['goal1','goal2','goal3']
我需要一个返回的列表:
result = [['node1','node2','node3','node4','goal1'], ['node1','node2','node3','node4','goal2'], ['node1','node2','node3','node4','goal3']]
这是我有的:
result = [] for i in range (len(list2)): list1.append(list2[i]) result.append(list1) list1.pop()
问题是,结果没有附加所需的值.它打印,
[['node1', 'node2', 'node3', 'node4'], ['node1', 'node2', 'node3', 'node4'], ['node1', 'node2', 'node3', 'node4']]
后for
循环完成.
我究竟做错了什么?
您可以list1
使用列表comp 将每个目标添加到list1的末尾:
list1 = ['node1', 'node2', 'node3', 'node4'] list2 = ['goal1', 'goal2', 'goal3'] print([list1 + [gl] for gl in list2])
输出:
[['node1', 'node2', 'node3', 'node4', 'goal1'], ['node1', 'node2', 'node3', 'node4', 'goal2'], ['node1', 'node2', 'node3', 'node4', 'goal3']]