用定界符分割字符串列表并添加到新列表 [英] Splitting a list of strings with a delimiter and adding to new lists
本文介绍了用定界符分割字符串列表并添加到新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的清单:
names = ['blue v orange', 'white v black', 'red v brown']
我想按' v '
拆分它们,并附加到这样的新列表中:
I want to split them by ' v '
and append to a new list like this:
['blue', 'white', 'red'] # first
['orange', 'black', 'brown'] # second
拆分后如何添加它们?以下代码不起作用:
How can I append them after splitting? The below code does not work:
first = []
second = []
for x in names:
first, second = x.split(' v ')
推荐答案
这是一个pythonic解决方案:
Here is a pythonic solution:
names = ['blue v orange', 'white v black', 'red v brown']
x, y = list(zip(*(k.split(' v ') for k in names)))
x # ('blue', 'white', 'red')
y # ('orange', 'black', 'brown')
这篇关于用定界符分割字符串列表并添加到新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文