Python - 有没有办法使用枚举来获取(str,index)而不是(index,str)?

时间:2017-03-16 02:57:55

标签: python enumerate

例如,

test = ["test1", "test2", "test3"]
print ([(i, test) for i, test in enumerate(test)])
>> [(0, 'test1'), (1, 'test2'), (2, 'test3')]

有没有办法改为[('test',0),('test2',1),('test3',2)]?

3 个答案:

答案 0 :(得分:1)

使用:

test = ["test", "test2", "test3"]
print ([(test1, i) for i, test1 in enumerate(test)])

我确实修复了您在开始代码中出现的小错字。我将i, test更改为i, test1

我将(i,test1)切换为(test1,i)

答案 1 :(得分:1)

除了明显的genexpr / listcomp包装器:

# Lazy
((x, i) for i, x in enumerate(test))

# Eager
[(x, i) for i, x in enumerate(test)]

你可以使用map(Py2上的future_builtins.map)和operator.itemgetter在C层进行反转以获得额外的速度:

from future_builtins import map  # Only on Py2, to get Py3-like generator based map

from operator import itemgetter

# Lazy, wrap in list() if you actually need a list, not just iterating results
map(itemgetter(slice(None, None, -1)), enumerate(test))

# More succinct, equivalent in this case, but not general reversal
map(itemgetter(1, 0), enumerate(test))

答案 2 :(得分:1)

你可以简单地在列表理解语句中切换变量。

test = ["test", "test2", "test3"]
print ([(test,i) for (i,test) in enumerate(test)])

结果:

[('test', 0), ('test2', 1), ('test3', 2)]
相关问题