简体   繁体   English

将列表索引拆分为新列表python

[英]Split list indexes into new lists python

I have an intro to programming lab using python. 我有一个使用python编程实验室的介绍。 I want to split a list: 我想拆分一个清单:

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

into two new lists: 分为两个新列表:

items_1 = ['40','10','30','4','18','40','76','10']

items_2 = ['40','40','40','5','40','40','80','10']

Any help is appreciated. 任何帮助表示赞赏。

So here is the standard zip one-liner. 所以这是标准的zip单线。 It works when items is non-empty. items非空时它可以工作。

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

items_1, items_2 = map(list, zip(*(i.split('/') for i in items)))

The map(list(..)) construct can be removed if you are happy with tuples instead of lists. 如果您对元组而不是列表感到满意,则可以删除map(list(..))构造。

I suggest something like this: 我建议像这样:

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']
items_1 = list()
items_2 = list()

for item in items:
  i_1, i_2 = item.split("/") #Split the item into the two parts
  items_1.append(i_1)
  items_2.append(i_2)

Result (from the IDLE shell) 结果 (来自IDLE shell)

>>> print(items_1)
['40', '10', '30', '4', '18', '40', '76', '10']
>>> print(items_2)
['40', '40', '40', '5', '40', '40', '80', '10']

It works even when items is empty. 即使 items是空的,它也能工作。

First split the elements of items (explained here ), then zip them (explained here ): 首先拆分items的元素( 在此解释),然后压缩它们( 在此解释):

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

items_tuples = map(lambda x: x.split('/'), items)

items_1, items_2 = zip(*items_tuples)

But note that this will cause a ValueError if you ever call it when items is empty. 但请注意,如果您在items为空时调用它,则会导致ValueError

You can try these methods : 您可以尝试以下方法:

items = ['40/40', '10/40', '30/40', '4/5', '18/40', '40/40', '76/80', '10/10']

print(list(zip(*[i.split('/') for i in items])))

or 要么

print(list(zip(*(map(lambda x:x.split('/'),items)))))

output: 输出:

[('40', '10', '30', '4', '18', '40', '76', '10'), ('40', '40', '40', '5', '40', '40', '80', '10')]

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

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