如何在python中拆分列表

时间:2022-12-28 00:32:47

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]? i.e.

假设我有一个列表['x1_0','x2_1','x3_0']如何将上面的列表拆分为两个列表,使得第一个列表包含['x1','x2','x3']和第二个列表列表[0,1,0]?即

         ('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

随意使用尽可能多的工具。这显然可以在一个for循环中完成,我知道。有一个更好的方法吗 ?。什么使用列表理解?阿尔斯

2 个解决方案

#1


6  

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

#2


1  

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.

你可以这样做。

#1


6  

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

#2


1  

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.

你可以这样做。