如何在Python中展平嵌套列表?

时间:2013-12-27 08:49:46

标签: python list

我的清单是:

 [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal'],........]

我想像这样展示

 ['kukatpally', 'gachibowli', 'Madhapur', 'Chintal',....]

所以如何删除那些'['和']'符号..

提前致谢

4 个答案:

答案 0 :(得分:4)

使用itertools.chain

import itertools

l = [['kukatpally', 'somethingelse'], ['gachibowli'], ['Madhapur'], ['Chintal']]

list(itertools.chain(*l))
>> ['kukatpally', 'somethingelse', 'gachibowli', 'Madhapur', 'Chintal']

itertools.chain.from_iterable

import itertools

l = [['kukatpally', 'somethingelse'], ['gachibowli'], ['Madhapur'], ['Chintal']]

list(itertools.chain.from_iterable(l))
>> ['kukatpally', 'somethingelse', 'gachibowli', 'Madhapur', 'Chintal']

答案 1 :(得分:3)

假设您的子列表可能包含多个项目:

 >>> ls = [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal']]
 >>> new_list = [item for sublist in ls for item in sublist]
 >>> new_list
 ['kukatpally', 'gachibowli', 'Madhapur', 'Chintal']

答案 2 :(得分:1)

>>> ls = [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal']]
>>> l = [x[0] for x in ls]
>>> l
['kukatpally', 'gachibowli', 'Madhapur', 'Chintal']
>>> 

答案 3 :(得分:0)

new_list = [item[0] for item in old_list]