简体   繁体   中英

How do I split the lists in python

Suppose I have a list ['x1_0','x2_1','x3_0'] How can I split the above list into two lists such that the first list contains ['x1','x2','x3'] and the second list [0,1,0] ? ie

         ('x1_0')
         /    \
        /      \
       /        \
     1st list   2nd list
      'x1'          0

Feel free to use as many tools as possible. This could obviously done in a single for loop ,which I am aware of. Is there a better way to do this ?. Something which uses list comprehension ? Als

You can use zip and a list comprehension :

>>> zip(*[i.split('_') for i in l])
[('x1', 'x2', 'x3'), ('0', '1', '0')]

And if you want to convert the second tuple's elements to int you can use the following nested list comprehension :

>>> [[int(i) if i.isdigit() else i for i in tup] for tup in zip(*[i.split('_') for i in l])]
[['x1', 'x2', 'x3'], [0, 1, 0]]

The preceding way is the proper way to do this task but as you say in comment as a smaller solution you can use map :

>>> l=[l[0],map(int,l[1])]
>>> l
[('x1', 'x2', 'x3'), [0, 1, 0]]
k=["x1_0","x2_1","x3_0"]
k1=[x.split("_")[0] for x in k]
k2=[int(x.split("_")[1]) for x in k]

You can do this simply this way.

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