python - 比较两个列表,如果相等则替换第三个列表中的值

我目前正在学习 Python 的在线初学者类(class),并且一直坚持这一要素。

我有

listA = ['a','d','g','p','l','g','r','e']

listB = ['a','p','p','l','e']

listC = ['_','_','_','_','_']

我正在比较列表 a 中的字母以查看它们是否在列表 B 中,如果为真则用该字母替换列表 C 中的相同索引。以下代码在函数中:

for a in listA:
        for b in listB:
            if a==b:
                listC.append(listB.index(b))
    stringC = str(listC)    
    print(stringC)  
    

问题是列表 C 被追加到正确的位置,但索引的值为 int。

如何替换字母而不是索引值?

非常感谢!

最佳答案

你可以在不需要调用索引的情况下进行反向搜索,这使得它更快(特别是如果 listA 比 listB 长,搜索将更短)并且最后使用列表理解(这再次比循环更快):

listC = [x if x in listA else '_' for x in listB]

另请注意,这种处理重复项的方式是自动的,而且更容易。

示例输出:

listC
['a', 'p', 'p', 'l', 'e']

https://stackoverflow.com/questions/62698794/

相关文章:

angular - 在 Angular 中使用 SystemJs 导入时找不到模块

python-3.x - 无法在 Python 3.8 上运行 Supervisor

java - Bootstrap 类路径未与 -source 8 一起设置

https - create-react-app:如何使用 https 但带有签名证书?

python - 如何将 tkinter 事件用于 'continue' 或暂停不同的 while

selenium - AWS Lambda 中的 Chrome Headless 返回空白页面

vim - 如何让 google cloud shell 在 vi​​m 中正确识别 Esc 键

vue.js - 如何使用 vue-router 处理错误

azure - 雪花 - Azure 事件目录集成

oracle - 如何使用 UTF8 作为国家字符集在 docker 中创建 Oracle 数据库?