在Python中,我们可以使用python:当我使用map()时,可以访问元素的索引吗?
map(lambda word: someFunction(element), data)
但我可以访问索引告诉正在访问哪些元素?
map(lambda word: someFunction(word,indexOfcurrentelement), data)
在Python中,我们可以使用python:当我使用map()时,可以访问元素的索引吗?
map(lambda word: someFunction(element), data)
但我可以访问索引告诉正在访问哪些元素?
map(lambda word: someFunction(word,indexOfcurrentelement), data)
你可以,如果你列举首位。
map(lambda (index, word): someFunction(word, index), enumerate(data))
>>> map(lambda (i, x): [i, x], enumerate(['a', 'b', 'c']))
[[0, 'a'], [1, 'b'], [2, 'c']]
然而,它开始变得复杂的时候,我个人更喜欢切换到for
:
for i, x in enumerate(sequence):
# do something with each 'x'
# 'i' is the index
如果不希望使用“拉姆达”在这里是一种方法:
x=[50,100,150]
index = []
for i in x:
indexis=x.index(i)
index = index+[indexis]
for a, b in zip(index, x):
print (a,b)
谢谢,我需要什么。 – goh 2011-04-25 05:05:08
这不适用于Python 3.x. – pillmuncher 2011-04-25 10:56:35