# DECLARING A SET
set1 = {'product','document','light','time','run'}
set2 = {'survival','shop','document','run'}
# Notice the use of {} instead of []
# FOR LOOP
for word in matching_words:
print(word)
# document
# run
matching_words = []
notmatching_words = list(list2) # copying the list2
for i in list1:
if i in list2:
matching_words.append(i) # appending the match
notmatching_words.remove(i) # removing the match
else:
notmatching_words.append(i) # appending the un-matched
回答的解决方案工作得非常好,但我想提出另一个使用
set
数据结构的解决方案,因为这是最适合此类问题的解决方案:请注意,元素的顺序是随机的
但是,如果顺序不重要,您甚至可能希望从头到尾使用集合:
如果您确实需要一个列表,您可以转换回结果(顺序仍然不可预测):
尝试:
这使得:
或者,您可以使用集合匹配:
相关问题 更多 >
编程相关推荐