[英]find occurrences of elements of a list in a list of list
i have a list [1, 2, 3]
我有一个列表
[1, 2, 3]
i want to find number of times the elements of this list appears in a list of list:我想查找此列表的元素出现在列表列表中的次数:
lol = [[1, 2, 4, 5], [2, 3, 1, 2], [1, 2, 3], [3, 2, 6, 7, 1], [1, 4, 2, 6, 3]]
occurrences = 4
What I'm doing currently is the following:我目前正在做的是以下内容:
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))
This method works but is quite slow when I have 100s of 1000s of list to compare with a list of list ( lol
remains static!)这种方法有效,但是当我有 100 个列表的 1000 个列表与列表列表进行比较时,速度很慢(
lol
保持静态!)
can we also preserve the "order" of the elements?我们还可以保留元素的“顺序”吗? there can be other elements in between.
中间可以有其他元素。 in this case
occurrences
will be 2 for the above case在这种情况下,上述情况的
occurrences
将为 2
Why not try:为什么不试试:
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.
This should work这应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.