好的,对于一个有趣的项目,我正在研究一些python我正在用一个基本的任务来打一堵墙:我需要比较列表中每个列表中共享的项目的时间名单。运用
shared_items = set(alist).intersection(blist)
gives me the items shared
在列表之间,但它没有告诉我,这些项目在每个列表中出现的频率。
我试过这样的循环,例如:
def the_count(alist,blist):
c = 0
for x in alist:
for y in blist:
if x == y:
c += 1
return c
但这并没有成功。
另一种尝试是使用Counter:
c = Counter(alist)
b = Counter(blist)
但试图循环计数器结果也失败了,最后一次尝试是
a = Counter(alist)
b = Counter(blist)
for key, val in a:
if key in b:
val1 = b[key]
if val < val1:
print b[key]
else:
print a[key]
答案 0 :(得分:2)
你几乎使用了集合intersection
。由于这为您提供了两个列表中的共同元素,因此您现在要做的就是循环遍历并计算元素。一种方法可能是:
list1 = [0, 1, 2, 3, 1, 2, 3, 4, 3, 2]
list2 = [1, 4, 3, 5, 2, 1, 0, 2, 7, 8]
shared = set(list1).intersection(list2)
# Now, loop over the elements and create a dictionary using a generator.
# The key will be the shared element, and the value would be a tuple
# which corresponds to the counts of the first list and the second list, respectively
counts = {num:(list1.count(num), list2.count(num)) for num in shared}
counts
现在包含:
{
0: (1, 1),
1: (2, 2),
2: (3, 2),
3: (3, 1),
4: (1, 1)
}
这可以进一步抽象成类似于以下的函数:
def count_shared_elements(list1, list2):
shared = set(list1).intersection(list2)
return {num:(list1.count(num), list2.count(num)) for num in shared}
答案 1 :(得分:1)
使用list(dict)作为jrd1指向理解:
>>> list1 = [0, 1, 2, 3, 1, 2, 3, 4, 3, 2]
>>> list2 = [1, 4, 3, 5, 2, 1, 0, 2, 7, 8]
>>> {i:(list1.count(i), list2.count(i)) for i in set(list1) & set(list2)}
{0: (1, 1), 1: (2, 2), 2: (3, 2), 3: (3, 1), 4: (1, 1)}
答案 2 :(得分:-1)
看看问题评论中链接的答案,另一种方法是这样:
for a in alist:
c+= blist.count(a)
答案 3 :(得分:-1)
最好的方法是从两个列表中获取唯一项目,并检查每个列表中这些不同数字的计数。
for distinct_num in set(alist + blist):
print(alist.count(distinct_num))
print(blist.count(distinct_num))