【问题标题】:using python to compare lists使用python比较列表
【发布时间】:2011-11-07 22:42:07
【问题描述】:

我在 python 中有三个列表。前两个包含字符串,第三个包含与第一个匹配的 id。

我想将第二个列表中的字符串与第一个列表中的所有术语进行比较,当我找到相同的字符串时,我想从第三个列表中获取 id 并替换第二个列表中的字符串。

例如

list1 = ['hello, 'bye', 'third']
list2 = ['bye', 'second', 'forth']
list3 = [100, 150, 60] 

如您所见,常用术语是bye。所以我想从list3中取出id(即150,对应list1中的字符串)并用这个id替换list2中的'bye'字符串。

有没有简单的方法用 python 做到这一点?

【问题讨论】:

    标签: python list python-3.x


    【解决方案1】:

    首先,构造一个字典,将list1 中的字符串映射到对应的id。然后,使用列表推导来应用映射:

    list1 = ["hello", "bye", "third"]
    list2 = ["bye", "second", "forth"]
    list3 = [100, 150, 60] 
    d = dict(zip(list1, list3))
    print([d.get(x, x) for x in list2])
    

    打印

    [150, 'second', 'forth']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2018-08-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多