[英]Split a list of strings by comma
I want to convert我想转换
['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
in to进入
['60', '78', '70', '77'.. etc]
I thought I could use我以为我可以用
for word in lines:
word = word.split(",")
newlist.append(word)
return newlist
but this produces this instead:但这会产生这个:
[['60', '78'], ['70', '77'], ['80', '74'], ['90', '75'], ['100', '74'], ['110', '75']]
Can anyone please offer a solution?任何人都可以提供解决方案吗?
You need to use list.extend
instead of list.append
.您需要使用list.extend
而不是list.append
。
newlist = []
for word in lines:
word = word.split(",")
newlist.extend(word) # <----
return newlist
Or, using list comprehension :或者,使用列表理解:
>>> lst = ['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
>>> [x for xs in lst for x in xs.split(',')]
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']
str.split
actually returns a list. str.split
实际上返回一个列表。
Return a list of the words in the string, using sep as the delimiter string.返回字符串中单词的列表,使用sep作为分隔符字符串。
Since you are appending the returned list to newlist
, you are getting a list of lists.由于您将返回的列表附加到newlist
,您将获得一个列表列表。 Instead use list.extend
method, like this而是使用list.extend
方法,就像这样
for word in lines:
newlist.extend(word.split(","))
But you can simply use nested list comprehension like this但是您可以像这样简单地使用嵌套列表理解
>>> data = ['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
>>> [item for items in data for item in items.split(",")]
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']
using itertools.chain :使用itertools.chain :
from itertools import chain
print(list(chain.from_iterable(ele.split(",") for ele in l)))
['60', '78', '70', '77', '80', '74', '90', '75', '100', '74', '110', '75']
The more items you have to flatten chain does it a bit more efficiently:您必须压平链的项目越多,它的效率就越高:
In [1]: l= ["1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20" for _ in range(100000)]
In [2]: from itertools import chain
In [3]: l= ["1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30" for _ in range(10000)]
In [4]: timeit (list(chain.from_iterable(ele.split(",") for ele in l)))
100 loops, best of 3: 17.7 ms per loop
In [5]: timeit [item for items in l for item in items.split(",")]
10 loops, best of 3: 20.9 ms per loop
I think this was the easiest way (thanks to a friend who helped with this)我认为这是最简单的方法(感谢帮助解决此问题的朋友)
list=['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']
for word in list:
chapter, number = word.split(',') #word = word.split(',')
print(word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.