[英]Python list of tuples, need to unpack and clean up
假设你有一个列表如
x = [('Edgar',), ('Robert',)]
什么是最有效的方式来达到字符串'Edgar'
和'Robert'
?
例如,不要真的需要x [0] [0]。
简单的解决方案,在大多数情况下最快。
[item[0] for item in x]
#or
[item for (item,) in x]
或者,如果您需要一个功能接口来索引访问(但稍慢):
from operator import itemgetter
zero_index = itemgetter(0)
print map(zero_index, x)
最后,如果序列太小而无法放入内存中,则可以迭代执行此操作。 这在集合上要慢得多,但只使用一个项目的内存。
from itertools import chain
x = [('Edgar',), ('Robert',)]
# list is to materialize the entire sequence.
# Normally you would use this in a for loop with no `list()` call.
print list(chain.from_iterable(x))
但是如果你要做的就是迭代,你也可以只使用元组解包:
for (item,) in x:
myfunc(item)
列表理解非常简单:
x = [('Edgar',), ('Robert',)]
y = [s for t in x for s in t]
这与list(itertools.chain.from_iterable(x))
作用相同,并且在行为上等效于以下代码:
y = []
for t in x:
for s in t:
y.append(s)
我需要将此字符串发送到另一个函数。
如果您的目的只是为列表中的每个字符串调用一个函数,那么就不需要构建新的列表了,只需...
def my_function(s):
# do the thing with 's'
x = [('Edgar',), ('Robert',)]
for (item,) in x:
my_function(item)
......或者如果你准备牺牲性能的可读性,我怀疑这是最快的...
def my_function(t):
s = t[0]
# do the thing with 's'
return None
x = [('Edgar',), ('Robert',)]
filter(my_function, x)
map()
和filter()
都将在C中进行迭代,而不是Python字节码,但map()
需要构建一个与输入列表长度相同的值列表,而filter()
只会构建一个空列表,只要my_function()
返回'falsish'值。
这是一种方式:
>>> [name for name, in x]
['Edgar', 'Robert']
注意逗号的位置,它解压缩元组。
>>> from operator import itemgetter
>>> y = map(itemgetter(0), x)
>>> y
['Edgar', 'Robert']
>>> y[0]
'Edgar'
>>> y[1]
'Robert'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.