python - Python map() 是否允许索引?

标签 python string dictionary replace

有什么方法可以获取映射函数的列表的索引?我已经让 map 几乎可以工作了,但我能够访问我的 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)

目前,我只想用 中所述单词的索引替换出现在 full_chunk 中的 long_words 的每个单词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.'

如果我需要提供更多信息,请告诉我,在此先感谢您的帮助!

最佳答案

使用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.'

关于python - Python map() 是否允许索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31882164/

相关文章:

PHP 字符串替换为字符串结尾

javascript - 使用react.js无法正确显示传单弹出字符串html

python - 自动化无聊的东西-第5章-国际象棋字典验证器

python - AES-ECB加密(Python Crypto.Cipher与openssl的区别)

python - Python 中的参数计数语法错误

python - 我怎么知道为什么在 SQLAlchemy 中发生回滚?

java - 字符串输出 -> System.out.println 分解

python - 合并 pandas 数据框中的多行并创建新列

Python:获取命令输出并放入字典同时删除字符

python - 展平字典的字典(2 层深)列表