在python中,以这种方式添加两个列表:['a','b']+['c']=[[a','b'],['c']。我该怎么做?

2024-09-27 21:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何添加两个列表,以使生成的列表保持其他列表不变:

['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')])

Tags: 代码inapp列表newfordeftemp
2条回答

+意味着对象的串联,所以直观地说:

[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]]

如果你想变得有趣,你可以使用特殊的variable argument operator, *

>>> 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函数不是很有用,因为输入和输出完全相同。你知道吗

它不是添加列表,而是附加列表。只需使用.append()就很容易了

只要做:

resulting_list = []
resulting_list.append(lista)
resulting_list.append(listb)
resulting_list.append(listc)

所有原始列表将保持不变,resulting_list将包含联接的列表。你想做什么并不完全清楚。你知道吗

相关问题 更多 >

    热门问题