【问题标题】:Python: compare two lists and update multiple valuesPython:比较两个列表并更新多个值
【发布时间】:2014-04-18 02:14:59
【问题描述】:

这是一个后续问题:Python: Compare two lists and update value in list2 based on value in list1

我有两个列表:

words = ['vestments', 'absence', 'windless']
prons = ['vEstm@nts', 'abs@nts', 'wIndl@s']

word中符合if条件的项目,处理pron中对应的项目。 例如,如果在word 中的某个项目中找到“less”,则将l@s 更改为lIs。如果在word 中没有发现nts 是字符串的一部分,则将@nts 替换为pron 中的@ns。

我试过了:

for (i, word) in enumerate(words):
if "less" in word:
    prons[i] = '\n'.join(prons[i])
    prons[i] = prons[i].replace("l@s", "lIs")
if "nts" not in word:
    prons[i] = prons[i].replace("@nts", "@ns")

期望的输出:

pron = ['vEstm@nts', 'abs@ns', 'wIndlIs']

但是我的输出是:

pron = ['vEstm@ns', 'abs@ns', 'wIndlIs']

如果有条件,我的“nts”中的代码似乎完全没有读取,任何提示将不胜感激。

【问题讨论】:

  • 请用单词描述它应该做什么。谢谢
  • 这里的逻辑到底是什么?
  • 一个问题(您向我们展示的内容)是您将列表命名为 wordpron,但遍历 wordsprons
  • @sshashank124 感谢您的反馈,已编辑。
  • 当我运行此代码时,我得到的结果与您在此处发布的结果不同。 (我从编写的代码中得到了我期望的结果。)你搞混了。

标签: python string list


【解决方案1】:

你可以通过如下两遍来做到这一点:

result = [b.replace('l@s', 'lIs') if 'less' in a else b for a,b in zip(words, prons)]
result = [b.replace('@nts', '@ns') if 'nts' not in a else b for a,b in zip(words, result)]

更新

我已将通行证压缩为一个通行证,如下所示:

result = [b.replace('l@s', 'lIs') if 'less' in a else b.replace('@nts', '@ns') if 'nts' not in a else b for a,b in zip(words, prons)]

>>> print result
['vEstm@nts', 'abs@ns', 'wIndlIs']

【讨论】:

  • 我收到AttributeError: 'list' object has no attribute 'replace'
  • @user1899415,你确定你使用的代码和我上面提供的完全一样吗,因为我测试过它并且工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多