【问题标题】:how to merge 2 lists of strings with the and operator如何使用 and 运算符合并 2 个字符串列表
【发布时间】:2021-11-15 22:06:26
【问题描述】:

我正在尝试使用 AND 运算符合并 2 个列表,如下所示:

testlist1 = inverted_index['amsterdam']
testlist2 = inverted_index['utrecht']
merged_testlist = []
for i in testlist1:
    for index in testlist2:
        if i in testlist1 and i in testlist2 and i not in merged_testlist:
            merged_testlist.append(i)
            
            
            
print(merged_testlist)


两个列表都由整数列表组成,testlist1 如下所示: [9756244, 16916567, 21859206, 25186285, 26784347, 29218587, 29406610, 33741990]

我从代码中得到的结果是一个空列表。如何遍历两个列表,使用 AND 运算符查看两个列表中的索引,并将它们附加到我的空 merge_testlist?

【问题讨论】:

  • 首先,i in testlist1 总是正确的。如果你想防止重复,使用一个集合,然后你可以删除i not in merged_testlist...那么,现在解释一下i in testlist2应该测试什么?
  • 迭代一个列表(仅)。对于该列表中的每个项目,查看它是否在第二个列表中。如果是,请将其添加到您的结果列表中。或者将list(set(a) & set(b)) 用于列表a 和b 的(列表)交集。

标签: python list loops


【解决方案1】:

您可以使用setintersection 来执行此操作。

testlist1 = inverted_index['amsterdam']
testlist2 = inverted_index['utrecht']
merged_testlist = list(set(testlist1).intersection(set(testlist2))
print(merged_testlist)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2017-09-11
    • 2022-09-27
    • 2018-05-22
    相关资源
    最近更新 更多