[英]How do I flatten nested lists in Python?
My List is : 我的清单是:
[['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal'],........]
I want to show like this 我想这样显示
['kukatpally', 'gachibowli', 'Madhapur', 'Chintal',....]
so how to delete those '[' and ']' symbols.. 那么如何删除那些'['和']'符号。
Thanks in advance 提前致谢
Use itertools.chain : 使用itertools.chain :
import itertools
l = [['kukatpally', 'somethingelse'], ['gachibowli'], ['Madhapur'], ['Chintal']]
list(itertools.chain(*l))
>> ['kukatpally', 'somethingelse', 'gachibowli', 'Madhapur', 'Chintal']
Or itertools.chain.from_iterable 或者itertools.chain.from_iterable
import itertools
l = [['kukatpally', 'somethingelse'], ['gachibowli'], ['Madhapur'], ['Chintal']]
list(itertools.chain.from_iterable(l))
>> ['kukatpally', 'somethingelse', 'gachibowli', 'Madhapur', 'Chintal']
Assuming you meant that your sub lists might contain multiple items: 假设您的意思是您的子列表可能包含多个项目:
>>> ls = [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal']]
>>> new_list = [item for sublist in ls for item in sublist]
>>> new_list
['kukatpally', 'gachibowli', 'Madhapur', 'Chintal']
>>> ls = [['kukatpally'], ['gachibowli'], ['Madhapur'], ['Chintal']]
>>> l = [x[0] for x in ls]
>>> l
['kukatpally', 'gachibowli', 'Madhapur', 'Chintal']
>>>
new_list = [item[0] for item in old_list]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.