我有元组列表(mytuples
)和列表列表(mylist
)。
我想找出每个列表中的元组中的每个元组出现多少次。
说元组(2,3)
出现在[1,2,3,4]
,[2,3,4,5]
和[2,3]
中。因此,(2,3)
的计数为3
。
元组和列表大小可以不同。
mytuples = [(2,3), (3,6), (1,2)]
mylist = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]]
count={}
for m in mytuples :
counter = 0
for i in mylist :
if set(m).issubset(i):
counter = counter + 1
count[m]=counter
我的输出是
{(2,3):3, (3,6): 0, (1,2):1}
这种方法效果很好,但是当我的列表很大(例如有1000条记录)时,这将花费更多时间。可以更快地完成吗?有什么建议么?
最佳答案
只需稍作调整,即可使您当前的算法更快一些:
# Your input data.
tuples = [(2,3), (3,6), (1,2)]
lists = [[1,2,3,4],[2,3,4,5],[2,3],[4,5,6]]
# Convert to sets just once, rather than repeatedly
# within the nested for-loops.
subsets = {t : set(t) for t in tuples}
mainsets = [set(xs) for xs in lists]
# Same as your algorithm, but written differently.
tallies = {
tup : sum(s.issubset(m) for m in mainsets)
for tup, s in subsets.items()
}
print(tallies)
关于python - Python-在列表列表中查找元组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49598695/