简体   繁体   中英

How to break a python list tuple into tuple with two elements?

I have a list and want to split each elements into a tuple of two elements.

The list looks like:

 list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']

How do I create a list of the form:

modified_list = [('dr.naman','5'),('dr.akanksha','7'),('dr.sumant','3')]

Try the following.

>>> list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']
>>> [tuple(s.split('_')) for s in list_doctors]
[('dr.naman', '5'), ('dr.akanksha', '7'), ('dr.sumant', '3')]

Use split() .

>>> list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']
>>> modified_list = [item.split('_') for item in list_doctors]
>>> modified_list
[['dr.naman', '5'], ['dr.akanksha', '7'], ['dr.sumant', '3']]

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