简体   繁体   中英

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 :

import itertools

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM