我有一个列表[1, 2, 3]
我想查找此列表的元素出现在列表列表中的次数:
lol = [[1, 2, 4, 5], [2, 3, 1, 2], [1, 2, 3], [3, 2, 6, 7, 1], [1, 4, 2, 6, 3]]
occurrences = 4
我目前正在做的事情如下:
a = [1, 2, 3]
lol = [[1, 2, 4, 5], [2, 3, 1, 2], [1, 2, 3], [3, 2, 6, 7, 1], [1, 4, 2, 6, 3]]
def get_count(a, b):
a = set(a)
return sum([a.issubset(x) for x in b])
print(get_count(a, lol))
此方法有效,但是当我有1000个列表中的100个要与列表列表进行比较时(lol
保持静态!)
我们还可以保留元素的“顺序”吗?两者之间可能还有其他元素。在这种情况下,occurrences
在上述情况下将为2
答案 0 :(得分:0)
为什么不尝试:
testlist = lol ##Create a test list that we will work with
for i in range len(testlist): ##Start a loop that will repeat length of testlist times
if a in testlist: ##If/When it finds the first occurrence of the list a
Occurrences =+ 1 ##It adds 1 to the amount off occurences
Pos = testlist.index(a)
testlist.del(Pos) ##It deletes the instance from the list.
这应该有效