![](/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.