Python元组列表,需要解压缩和清理

时间:2013-04-30 16:09:02

标签: python python-2.7

假设您有一个列表,例如

x = [('Edgar',), ('Robert',)]

获得字符串'Edgar''Robert'的最有效方法是什么?

例如,不要真的需要x [0] [0]。

5 个答案:

答案 0 :(得分:6)

简单的解决方案,在大多数情况下最快。

[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)

答案 1 :(得分:3)

使用list comprehension

非常简单
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)

答案 2 :(得分:2)

  

我需要将此字符串发送到另一个函数。

如果您的目的只是为列表中的每个字符串调用一个函数,那么就不需要构建新的列表了,只需要...

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()返回'falsish'值,my_function()只会构建一个空列表。

答案 3 :(得分:2)

这是一种方式:

>>> [name for name, in x]
['Edgar', 'Robert']

注意逗号的位置,这会解开元组。

答案 4 :(得分:1)

>>> from operator import itemgetter
>>> y = map(itemgetter(0), x)
>>> y
['Edgar', 'Robert']
>>> y[0]
'Edgar'
>>> y[1]
'Robert'