简体   繁体   English

如何在python中拆分列表

[英]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] ? 假设我有一个列表['x1_0','x2_1','x3_0']如何将上面的列表拆分为两个列表,使得第一个列表包含['x1','x2','x3']和第二个列表列表[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. 这显然可以在一个for循环中完成,我知道。 Is there a better way to do this ?. 有一个更好的方法吗 ?。 Something which uses list comprehension ? 使用列表理解的东西? Als 阿尔斯

You can use zip and a list comprehension : 您可以使用zip和列表理解:

>>> 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,可以使用以下嵌套列表推导:

>>> [[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 : 前面的方法是执行此任务的正确方法,但是正如您在注释中所说的那样,可以使用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. 你可以这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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