![](/img/trans.png)
[英]How to remove dictionary from list of dictionary if value repeats in items
[英]How to count the number of repeats for an item in a list which is a value in a dictionary?
所以我有一个字典(dictionary2),其中每个值都是一个列表。 我需要制作一个 function,在 plot 上显示此数据,并在 x 轴上显示我管理的键。 我想创建一个单独的列表(count_list),其中包含每个数字在属于给定键的列表中重复的频率(只有一个单独的列表用于字典的所有值一起)。 最终目标是创建一个重叠标记更大的散点图,我可以通过将这个单独的列表归因于散点图调用中的 's' 参数来实现。 (请注意,不同的颜色或其他东西也可以正常工作,但仍然需要 count_list )
我有 1 个不考虑重叠的工作版本(这可能会给出一些上下文,见下文)。
我目前正在尝试使用以下代码制作 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)
这将返回一个 count_list,其中每个键都重复相同的数字序列。 我意识到我的代码可能太简单了,所以我并不惊讶它没有工作。 但是,我不确定 go 从这里到哪里,也不明白为什么 output 看起来像那样。
当前的 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)
(我使用的是 jupyterlab 3.0.14。)
这是我第一次在堆栈溢出中发布问题,所以如果我违反了任何礼仪,或者我对问题的解释中有任何不清楚的地方,请告诉我!
我不确定我是否正确理解了您的需求,但是是这样吗?
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)
output如下:
{
"key1": {1: 2, 2: 1, 3: 1, 4: 2},
"key2": {1: 2, 2: 3, 5: 1},
"key3": {100: 2, 3: 1, 9: 1},
}
您会得到一个与原始键具有相同键的字典,并且在每个键中,您都有一个字典,其中包含相应列表中每个数字的出现次数
我不知道您是要对每个字典的值求和还是全部求和,但我会尝试实现并适应您的特定用途。
使用列表压缩可以分解项目:
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.