Python map()是否允许索引?

时间:2015-08-07 16:05:32

标签: python string dictionary replace

有没有办法获取列表的索引,哪个映射函数?我已经让地图几乎正常工作,但我能够访问long_words列表中的特定项目

# full_chunk is a very long string of plaintext (eg:pages from a book)
# long_words is a list of words for which I wish to substitute other things

# works
for x in xrange(len(long_words)):
    full_chunk = full_chunk.replace(long_words[x],str(x))

# doesn't work :(
subber = lambda a,b,c: a.replace(b,c)
map(subber(full_chunk,long_words[long_words.index(x)],long_words.index(x)),long_words)

目前,我只希望能够用long_words列表中所述单词的索引替换full_chunk中出现的long_words的每个单词的每次出现。例如:

# example input
long_words = ['programming','pantaloons']
full_chunk = 'While programming, I prefer to wear my most vividly-hued pantaloons.'

# desired output (which is what the for loop gives me)
print(full_chunk)
'While 0, I prefer to wear my most vividly-hued 1.'

如果我需要提供更多信息,请告知我们,并提前感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

使用enumerate(),您根本不需要map()

>>> long_words = ['programming', 'pantaloons']
>>> full_chunk = 'While programming, I prefer to wear my most vividly-hued pantaloons.'
>>> for i, word in enumerate(long_words):
...     full_chunk = full_chunk.replace(word, str(i))
...
>>> full_chunk
'While 0, I prefer to wear my most vividly-hued 1.'

答案 1 :(得分:2)

map在这里不太合适,因为你想获取函数第一次调用的返回值,并将其作为参数发送到第二次调用,等等。 map无法以这种方式链接项目(除非您使用global值或类似值的技巧),但map的朋友reduce可以:

>>> long_words = ['programming','pantaloons']
>>> full_chunk = 'While programming, I prefer to wear my most vividly-hued pantaloons.'
>>> print reduce(lambda s,(idx,word): s.replace(word,str(idx)), enumerate(long_words), full_chunk)
While 0, I prefer to wear my most vividly-hued 1.