假设您有一个列表,例如
x = [('Edgar',), ('Robert',)]
获取字符串的最有效方法是什么'Edgar'
and '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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)