用逗号分隔字符串列表

时间:2015-01-11 12:02:21

标签: python string list

我想转换

['60,78', '70,77', '80,74', '90,75', '100,74', '110,75']

进入

['60', '78', '70', '77'.. etc]

我以为我可以用

for word in lines:
    word = word.split(",")
    newlist.append(word)
return newlist

但这会产生这种情况:

[['60', '78'], ['70', '77'], ['80', '74'], ['90', '75'], ['100', '74'], ['110', '75']]

有人可以提供解决方案吗?

4 个答案:

答案 0 :(得分:5)

您需要使用list.extend代替list.append

newlist = []
for word in lines:
    word = word.split(",")
    newlist.extend(word)  # <----
return newlist

或者,使用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']

答案 1 :(得分:2)

str.split实际上会返回一个列表。

  

使用 sep 作为分隔符字符串,返回字符串中的单词列表。

由于您要将返回的列表附加到newlist,因此您将获得一个列表列表。而是使用list.extend方法,就像这样

for word in lines:
    newlist.extend(word.split(","))

但你可以简单地使用像这样的嵌套列表理解

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

答案 2 :(得分:0)

使用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']

平展链条所需的物品越多,效率就越高:

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

答案 3 :(得分:-1)

我认为这是最简单的方法(感谢为此提供帮助的朋友)

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)