您的位置:首页技术文章
文章详情页

python 两个列表添加

【字号: 日期:2022-07-06 09:42:35浏览:43作者:猪猪

问题描述

有一组列表,a,b,c,……,想要将这一组列表不断添加到同一个列表里面,比如:

`a = [’a’]b = [’b’]c = [’c’]addall = [[’a’], [’b’], [’c’]]`

只想到了用for循环来做这个,有什么比较pythonic的方法么?

问题解答

回答1:

没必要太在意形式,简洁易于理解就行

a = [’a’]b = [’b’]c = [’c’]tt=[]tt.append(a)tt.append(b)tt.append(c)print tt#输出[[’a’], [’b’], [’c’]]回答2:

In [1]: a = [’a’, ’b’, ’c’] In [2]: b = [’d’, ’e’, ’f’] In [3]: import itertools In [4]: itertools.chain(a, b) Out[4]: <itertools.chain at 0x30fcd90> In [5]: list(itertools.chain(a, b)) Out[5]: [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] 回答3:

python2,3

In [6]: a=[’a’]In [7]: b=[’b’]In [8]: a.extend(b)In [9]: aOut[9]: [’a’, ’b’]

python2,3,我觉得这个比较自然!

In [1]: a=[’a’]In [2]: b=[’b’]In [3]: a+bOut[3]: [’a’, ’b’]

python3

In [1]: a=[’a’]In [2]: b=[’b’]In [3]: [*a,*b]Out[3]: [’a’, ’b’]回答4:

d = [i for i in (a,b,c)]

标签: Python 编程
相关文章: