I am trying to merge 2 lists using the AND operator as follows:
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)
both lists are made of of a list of ints, testlist1 looks as follows: [9756244, 16916567, 21859206, 25186285, 26784347, 29218587, 29406610, 33741990]
the result I get from my code is an empty list. How do I iterate over both lists, see which indices are in both lists using the AND operator, and append them to my empty merge_testlist?
You can use a set
and intersection
to do it.
testlist1 = inverted_index['amsterdam']
testlist2 = inverted_index['utrecht']
merged_testlist = list(set(testlist1).intersection(set(testlist2))
print(merged_testlist)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.