【问题标题】:How to count the number of repeats for an item in a list which is a value in a dictionary?如何计算列表中作为字典中的值的项目的重复次数?
【发布时间】:2021-12-30 17:44:35
【问题描述】:

所以我有一个字典 (dictionary2),其中每个值都是一个列表。我需要创建一个函数,在绘图上显示这些数据,x 轴上的键是我管理的。我想创建一个单独的列表(count_list),其中包含每个数字在属于给定键的列表中重复的频率(只有一个单独的列表用于字典的所有值一起)。最终目标是创建一个重叠标记更大的散点图,我可以通过将这个单独的列表归因于散点图调用中的 's' 参数来实现。 (请注意,不同的颜色或其他东西也可以正常工作,但仍然需要 count_list )

我有 1 个不考虑重叠的工作版本(这可能会提供一些上下文,见下文)。

我目前正在尝试使用以下代码创建 count_list(为了方便实验,我将其放在函数之外):

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

这将返回一个 count_list,其中每个键都重复相同的数字序列。我意识到我的代码可能太简单了,所以我并不惊讶它没有工作。但是,我不确定从这里去哪里,也不明白为什么输出看起来像这样。

当前的情节是这样的:

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

(我使用的是 jupyterlab 3.0.14。)

这是我第一次在堆栈溢出中发布问题,所以如果我违反了任何礼仪或者我对问题的解释有什么不清楚的地方,请告诉我!

【问题讨论】:

  • 欢迎您,托林!你能分享你的数据集的一个小样本吗?它可能是一个“假”示例,但更容易重现您的代码。
  • 非常感谢您的回复(而且如此之快!),但是问题已经在其他用户的帮助下得到解决。

标签: python list dictionary graphics scatter-plot


【解决方案1】:

我不确定我是否正确理解了您的需求,但是是这样的吗?

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)

输出如下:

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

您会得到一个与原始键具有相同键的字典,并且在每个键中,您都有一个字典,其中包含相应列表中每个数字的出现次数

【讨论】:

  • 这不是我需要的输出,但是感谢您的代码,我能够到达那里。非常感谢!!我自己永远也想不通。 (如果您好奇:您的代码以字典的形式提供输出,而我需要以连续列表的形式使其适用于图形。这只需要对您的方法进行一些小的调整,所以功劳给你,非常感谢你。)
【解决方案2】:

我不知道您是要对每个字典的值求和还是全部求和,但我会尝试实现并适应您的特定用途。

使用列表压缩可以分解项目:

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)]

然后迭代:

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}

【讨论】:

    猜你喜欢
    • 2011-03-30
    • 2022-12-04
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多