在 Python3 中,我有一個字典{k = episode : value = count},我無法弄清楚如何按值相加的鍵的子字串進行分組。
輸入:
dict = {'S01E01': 27, 'S01E02': 27, 'S01E03': 32, 'S01E04': 36, 'S01E05': 35, 'S01E06': 31,
'S02E01': 33, 'S02E02': 21, 'S02E03': 20, 'S02E04': 29, 'S02E05': 33, 'S02E06': 42}
想要的輸出:
output_dict = {'S01': 188 , 'S02' : 178}
我嘗試建立一個季節的中間串列,并嘗試使用 reduce & counter 功能但沒有成功。
List = ['S01', 'S02']
還嘗試在這里尋找任何結果,但找不到任何結果。可能是錯誤的術語。任何幫助,將不勝感激。謝謝
uj5u.com熱心網友回復:
Onyambu 的答案可能是解決這個問題的更 Pythonic 的方法,但是如果您正在尋找適合此特定用例的更易于閱讀的解決方案,那么您可以執行以下操作:
episodes = {'S01E01': 27, 'S01E02': 27, 'S01E03': 32, 'S01E04': 36, 'S01E05': 35, 'S01E06': 31,
'S02E01': 33, 'S02E02': 21, 'S02E03': 20, 'S02E04': 29, 'S02E05': 33, 'S02E06': 42}
output = {}
for episode in episodes:
season = episode[0:3] #Gets the first 3 characters
if season not in output:
output[season] = episodes[episode]
else:
output[season] = episodes[episode]
print(output)
uj5u.com熱心網友回復:
使用dict理解:
from itertools import groupby
{key:sum(list(zip(*val))[1]) for key, val in groupby(d.items(), key = lambda x:x[0][:3])}
Out: {'S01': 188, 'S02': 178}
使用正常的 for 回圈首先將您的資料保存為d. 那么delete dict因為它是一個內部函式,即del dict。現在您可以運行以下代碼
result = dict()
for key, val in d.items():
var1 = key[:3]
if not result.get(var1):
result[var1] = 0
result[var1] = val
uj5u.com熱心網友回復:
我假設子項只有 3 個字符長。
dic = {'S01E01': 27, 'S01E02': 27, 'S01E03': 32, 'S01E04': 36, 'S01E05': 35, 'S01E06': 31,
'S02E01': 33, 'S02E02': 21, 'S02E03': 20, 'S02E04': 29, 'S02E05': 33, 'S02E06': 42}
首先提取唯一的子鍵:
subkeys = set([key[:3] for key in dic.keys()])
然后,使用字典理解來總結每個子鍵的值。
out = {subkey: sum([value for key, value in dic.items() if subkey in key]) for subkey in subkeys}
更丑的單線:
out = {subkey[:3]: sum([value for key, value in dic.items() if subkey[:3] in key]) for subkey in dic.keys()}
uj5u.com熱心網友回復:
另一種方法:
data = {'S01E01': 27, 'S01E02': 27, 'S01E03': 32, 'S01E04': 36, 'S01E05': 35, 'S01E06': 31,
'S02E01': 33, 'S02E02': 21, 'S02E03': 20, 'S02E04': 29, 'S02E05': 33, 'S02E06': 42}
from itertools import groupby
out = {}
for key, value in groupby(data, lambda x:x[:3]):
out[key] = sum([data[val] for val in list(value)])
print (out)
輸出:
{'S01': 188, 'S02': 178}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345604.html
