简体   繁体   English

如何计算列表中作为字典中的值的项目的重复次数?

[英]How to count the number of repeats for an item in a list which is a value in a dictionary?

So I have a dictionary (dictionary2) where every value is a list.所以我有一个字典(dictionary2),其中每个值都是一个列表。 I need to make a function that shows this data on a plot, with the keys on the x-axis, which I managed.我需要制作一个 function,在 plot 上显示此数据,并在 x 轴上显示我管理的键。 I want to create a separate list (count_list) that contains counts for how often each number repeats itself within the list belonging to a given key (only 1 separate list for all of the values of the dictionary together).我想创建一个单独的列表(count_list),其中包含每个数字在属于给定键的列表中重复的频率(只有一个单独的列表用于字典的所有值一起)。 The end goal is to create a scatterplot where overlapping markers are bigger, which I could do by ascribing this separate list to the 's' argument in the scatterplot call.最终目标是创建一个重叠标记更大的散点图,我可以通过将这个单独的列表归因于散点图调用中的 's' 参数来实现。 (Note that different color or something would work fine too but that would still require the count_list anyway) (请注意,不同的颜色或其他东西也可以正常工作,但仍然需要 count_list )

I have 1 working version that does not account for overlap (this might give some context, see below).我有 1 个不考虑重叠的工作版本(这可能会给出一些上下文,见下文)。

I'm currently trying to make the count_list with the following code (I took it outside of the function for experimenting convenience):我目前正在尝试使用以下代码制作 count_list (为了方便实验,我将它放在 function 之外):

count_list=[]
for key in dictionary2:
    for value in dictionary2:
        for M in value:
            count= value.count(M)
            count_list.append(count)

This returns a count_list with the same sequence of numbers being repeated for each key.这将返回一个 count_list,其中每个键都重复相同的数字序列。 I realize my code is probably way too simplistic, so I am not surprised it didn't work.我意识到我的代码可能太简单了,所以我并不惊讶它没有工作。 However, I'm not sure where to go from here and don't understand why the output looks like that.但是,我不确定 go 从这里到哪里,也不明白为什么 output 看起来像那样。

The current plot looks like this:当前的 plot 看起来像这样:

def plot_dict(dataset):
    
    #transforming data to be read correctly into the plot
    d = dataset
    x= []
    y= []
    for k, v in d.items():
        x.extend(list(itertools.repeat(k, len(v))))
        y.extend(v)
    
    plt.figure(figsize=(30,30))
    plt.plot(x,y, '.')
    plt.title('FASTA plot', fontsize=45)
    plt.xlabel('Sequence IDs', fontsize=30)
    plt.ylabel('Molecular weight', fontsize=30)
    plt.xticks(fontsize=15)
    plt.yticks(fontsize=15)
plot_dict(dictionary2)

enter image description here在此处输入图像描述

(I'm using jupyterlab 3.0.14.) (我使用的是 jupyterlab 3.0.14。)

This is my first time posting a question in stack overflow, so if I broke any kind of etiquette or if anything in my explanation of the problem was unclear, please let me know!这是我第一次在堆栈溢出中发布问题,所以如果我违反了任何礼仪,或者我对问题的解释中有任何不清楚的地方,请告诉我!

I'm not sure if I understood what you need correctly, but is it something like this?我不确定我是否正确理解了您的需求,但是是这样吗?

from typing import Dict


dictionary = {
    "key1": [1, 2, 3, 4, 4, 1],
    "key2": [1, 2, 2, 2, 1, 5],
    "key3": [100, 3, 100, 9],
}

occurrences_dict: Dict[str, Dict[int, int]] = {key: {} for key in dictionary}

for key, numbers_list in dictionary.items():
    for number in numbers_list:
        occurrences = numbers_list.count(number)
        occurrences_dict[key].update({number: occurrences})


print(occurrences_dict)

The output is the following: output如下:

{
    "key1": {1: 2, 2: 1, 3: 1, 4: 2},
    "key2": {1: 2, 2: 3, 5: 1},
    "key3": {100: 2, 3: 1, 9: 1},
}

You get a dictionary with the same keys as the original and within each key, you have a dictionary with the number of occurrences of each number on the corresponding list您会得到一个与原始键具有相同键的字典,并且在每个键中,您都有一个字典,其中包含相应列表中每个数字的出现次数

I don't know if you want sum the values of each dictionary or sum them all, but I will try to implement and you adapt to your specific use.我不知道您是要对每个字典的值求和还是全部求和,但我会尝试实现并适应您的特定用途。

Using list compreenssion is possible decompose the items:使用列表压缩可以分解项目:

d = {'key1': [1, 2, 3, 4, 4, 1], 'key2': [1, 2, 2, 2, 1, 5], 'key3': [100, 3, 100, 9]}

w = [(a,x,b.count(x)) for a,b in d.items() for x in set(b)]
# w = [('key1', 1, 2), ('key1', 2, 1), ('key1', 3, 1), ('key1', 4, 2), ('key2', 1, 2), 
#     ('key2', 2, 3), ('key2', 5, 1), ('key3', 9, 1), ('key3', 3, 1), ('key3', 100, 2)]

Then iterate:然后迭代:

d = dict()
for key,i,value in w:
    d[i] = value if i not in d else d[i]+value
# d = {1: 4, 2: 4, 3: 2, 4: 2, 5: 1, 9: 1, 100: 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果项目中的值重复,如何从字典列表中删除字典 - How to remove dictionary from list of dictionary if value repeats in items 命名列表中的每一项都是字典的值 - Naming each item in a list which is a value of a dictionary Python:将项目添加为列表,该列表是字典中的值 - Python: Adding an item a list which is a value in a dictionary 将项添加到字典列表中具有相同值的字典 - Add item to dictionary which has same value in list of dictionary 根据字典值计算列表中字典中的项目数 - Count the number of items in a dictionary inside a list as per the dictionary value Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats 如何计算一个值在字典中出现的次数? - How to count the number of times a value appears in a dictionary? 使用字典值列表计算列表交叉检查中最常见的项目 - Count most common item in list crosschecking with dictionary value lists 选择具有相同长度值的键,该键是字典中的最高计数列表 - Select keys with same length of value which is highest count list in dictionary 如何更新列表中的项,它是字典中键的值? - How to update an item in a list that is value to a key in a dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM