[英]How to scan a big list to find if all elements match the ones of a second, smaller, list?
I'm hvaing a hard time with a problem which I thought was pretty simple.我很难解决一个我认为很简单的问题。 I have two lists:我有两个清单:
list1 = ['A', 'B', 'C', 'D','E']
list2 = ['E', 'B', 'F', 'A', 'C', 'N'...]
I want to scan list2 and see if all of its elements are the same as the ones in list1.我想扫描 list2 并查看它的所有元素是否与 list1 中的元素相同。 If they are different, I want to see which are the elements that differ and cancel them from list2.如果它们不同,我想查看哪些元素不同并从 list2 中取消它们。 In this example, I want to print "F" and "N" from list2 and cancel them.在此示例中,我想从 list2 打印“F”和“N”并取消它们。
I tried:我试过了:
found = False
lenght2 = len(list2)
i = 0
for j in list1:
for i in range(0, lenght2):
if i != j:
found = True
#I don't know how to cancel i
print(i)
i = i + 1
break
However, the whole thing does not work.然而,整个事情都行不通。 Is there anyone who could help me?有没有人可以帮助我?
You could go through all of list2 then check if it is in list one, like this:您可以通过所有 list2 go 然后检查它是否在列表一中,如下所示:
for i in range(len(list2)):
if list2[i] in list1:
pass
else:
#Cancel list2[i] ? Or whatever.
There's no need to use nested loops here -- you are removing elements from list2
, based on information from list1
, so loop through list2
.此处无需使用嵌套循环——您要根据来自list1
的信息从list2
中删除元素,因此循环遍历list2
。
list1 = ['A', 'B', 'C', 'D', 'E']
list2 = ['E', 'B', 'F', 'A', 'C', 'N']
for e in list2[:]:
if e not in list1:
list2.remove(e)
print(list2)
This code loops through list2
and checks for each element ( e
) if it occurs in list1
.此代码循环遍历list2
并检查每个元素 ( e
) 是否出现在list1
中。 If not, it removes it from list2
.如果没有,它会将其从list2
中删除。
Note: the use of list2[:]
here rather than list2
is due to this .注意:这里使用list2[:]
而不是list2
是由于this 。
list1 = ['A', 'B', 'C', 'D', 'E']
list2 = ['E', 'B', 'F', 'A', 'C', 'N']
list2 = [e for e in list2 if e in list1]
print(list2)
See more about how list comprehensions work here . 在此处查看有关列表推导如何工作的更多信息。
In both cases, you should get:在这两种情况下,您都应该得到:
['E', 'B', 'A', 'C']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.