如何添加两个列表,以使结果列表保持完整列表:
['5','6','7'] + ['1'] + ['9','7'] = [['5','6','7'], ['1'], ['9','7']]
可以在Python中执行此操作?
当前代码:
def appendy(list_o_list):
temp_l = []
for l in list_o_list:
temp_l.append(list(l))
new_list=[]
new_list = [a + b for a, b in itertools.combinations(temp_l, 2)]
print("app",new_list)
return (new_list)
appendy([('g3', 'g1'), ('g3', 'g2')])
它不添加列表,它是附加列表。仅使用.append()
很容易只是做:
resulting_list = []
resulting_list.append(lista)
resulting_list.append(listb)
resulting_list.append(listc)
所有原始列表将保持不变,resulting_list
将包含连接的列表。您要做的事情并不完全清楚。
+
意味着对象的串联,因此直觉上:
[5, 6, 7] + [8, 9]
= [5, 6, 7, 8, 9]
Darkchili Slayer提到的,您通过附加列表将列表嵌入另一个列表中。实际上,一个相当简单的解决方案就是这样做:
Python 3.4.2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [5, 6, 7]
>>> b = [8, 9]
>>> c = []
>>> c.append(a)
>>> c.append(b)
>>> c
[[5, 6, 7], [8, 9]]
如果您想幻想,可以使用特殊变量参数操作员进行类似的操作, *:
>>> def join_l(*lists):
... temp = []
... for l in lists:
... temp.append(l)
... return temp
...
>>> join_l([5, 6, 7], [8, 9])
[[5, 6, 7], [8, 9]]
您甚至也可以这样做,并使阅读更容易:
def join_l(*lists):
... return list(lists)
...
>>> join_l([5, 6, 7], [8, 9])
[[5, 6, 7], [8, 9]]
最后,值得注意的是,列表有一个extend
功能,该功能在另一个列表中附加了每个项目。您可以使用它来简化第一个示例:
>>> a = [5, 6, 7]
>>> b = [8, 9]
>>> c = []
>>> c.extend([a, b])
>>> c
[[5, 6, 7], [8, 9]]
在这种情况下,extend
函数不是很有用,因为输入与其输出完全相同。