Python列表及其拆分

时间:2011-02-11 10:43:12

标签: python list

例如,我有这样的代码

a = ["a;b", "c;d",...,"y;z"]

我想将每个列表元素拆分为同一列表中的项目。所以我想得到这样的东西:

["a", "b", "c", "d", ...., "y", "z"]

我该怎么办?谢谢你的回答。

9 个答案:

答案 0 :(得分:9)

仅使用字符串操作似乎最简单(当然这是主观的)和最快(与目前为止发布的其他解决方案相比,差距很大)。

>>> a = ["a;b", "c;d", "y;z"]
>>> ";".join(a).split(";")
['a', 'b', 'c', 'd', 'y', 'z']

证明/基准

按经过时间的升序排序:

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '";".join(a).split(";")'
10000 loops, best of 3: 48.2 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '[single for pair in a for single in pair.split(";")]'
1000 loops, best of 3: 347 usec per loop

python -mtimeit -s'from itertools import chain; a=["a;b","x;y","p;q"]*99' 'list(chain(*(s.split(";") for s in a)))'
1000 loops, best of 3: 350 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum([x.split(";") for x in a],[])'
1000 loops, best of 3: 1.13 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum(map(lambda x: x.split(";"), a), [])'
1000 loops, best of 3: 1.22 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'reduce(lambda x,y:x+y, [pair.split(";") for pair in a])'
1000 loops, best of 3: 1.24 msec per loop

答案 1 :(得分:5)

您可以使用itertools.chain

>>> a = ["a;b", "c;d","y;z"]
>>> list(itertools.chain(*(s.split(';') for s in a)))
['a', 'b', 'c', 'd', 'y', 'z']

答案 2 :(得分:3)

更具功能性的方法:

>>> l = ["a;b", "c;d", "e;f", "y;z"]
>>> sum(map(lambda x: x.split(';'), l), [])
['a', 'b', 'c', 'd', 'e', 'f', 'y', 'z']

答案 3 :(得分:1)

这是工作:

l = []
for item in ["a;b", "c;d", "e;f"]:
     l += item.split(";")

print l

它给出了:

['a', 'b', 'c', 'd', 'e', 'f']

答案 4 :(得分:1)

a = ["a;b", "c;d","y;z"]
print [atom for pair in a for atom in pair.split(';')]

给出你想要的东西:

['a', 'b', 'c', 'd', 'y', 'z']

注意:我无法告诉你如何在阵列中间从'...'到'....':)

答案 5 :(得分:0)

l = []
for current in [c.split(';') for c in a]:
   l.extend(current)

您可能希望阅读列表推导http://docs.python.org/tutorial/datastructures.html#list-comprehensions

答案 6 :(得分:0)

a = ["a;b", "c;d","e;f","y;z"]
b = []
for i in a:
    c = i.split(';')
    b = b + c

print b

答案 7 :(得分:0)

比菲利克斯克林的回答有点长,但是这里有。首先将列表拆分为子列表

>>> a_split = [i.split(";", 1) for i in a]

这将产生一个表格列表:

[[a,b], [c,d], ..., [y,z]]

您现在需要以某种方式“合并”内部和外部列表。内置reduce()函数非常适合:

>>> reduce(lambda x, y: x + y, a_split)

瞧:

['a', 'b', 'c', 'd', ... 'y', 'z']

答案 8 :(得分:0)

字符串可用于此:

>>> a = ["a;b", "c;d","y;z"]
>>> list(''.join(a).replace(';', ''))
['a', 'b', 'c', 'd', 'y', 'z']

此解决方案是目前为止提出的最快的解决方案之一:

# Shawn Chin's solution (the fastest so far, by far):
python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '";".join(a).split(";")'
10000 loops, best of 3: 27.4 usec per loop

# This solution:
python -mtimeit -s'a=["a;b","x;y","p;q"]*99' "list(''.join(a).replace(';', ''))"
10000 loops, best of 3: 33.5 usec per loop

士气是在这种情况下由字符串表示的列表非常有效,可能是因为更简单的内存处理(字符存储在连续的内存位置)。