Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python map()是否允许索引?_Python_String_Dictionary_Replace - Fatal编程技术网

Python map()是否允许索引?

Python map()是否允许索引?,python,string,dictionary,replace,Python,String,Dictionary,Replace,有没有办法得到映射函数的列表的索引?我的地图几乎可以使用了,但我希望能够访问我的长单词列表中的特定项目 # 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

有没有办法得到映射函数的列表的索引?我的地图几乎可以使用了,但我希望能够访问我的
长单词列表中的特定项目

# 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\u words
列表中所述单词的索引替换出现在
full\u chunk
中的
long\u 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.'
请让我知道,如果我需要提供任何更多的信息,并提前感谢所有您的帮助

使用,您根本不需要
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.'

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


为了确保我理解
enumerate()
,这似乎是我的for循环和映射之间的一个中间点,对吗
enumerate()
看起来它的主要优点是不需要每次都从
长单词列表中提取值。是这样吗?@BenSandeen不确定你的意思,但基本上在Python中,你从不循环索引,而是循环元素:
对于我的列表中的元素:print(element)
。现在,当您使用enumerate时,您将获得元素和索引。因此,您可以循环遍历元素并获取它们的索引。
>>> 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.