在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