[英]scoring motifs in python dictionary
我在python中有一本字典,看起來像這樣:
raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}
如您所見,這些值是列表。 我想用分數代替列表。 我根據長度對列表中的每個字符評分。 如果長度是4到9,則它們將得到1,從10到15將是2和16,而更長的則將得到3。然后,我將每個id的所有分數加起來,並且每個id的分數將為1。 這是一個小例子:
score = {'id1': 3, 'id2': 2}
我嘗試了這段代碼:
score = {}
for val in raw.values():
for i in val:
if len(i) >=4 and len(i) <9:
sc = 1
elif len(i) >=10 and len(i) <15:
sc = 2
else:
sc = 3
score[raw.keys()] = sc
它沒有給我想要的東西。
我在您的示例中看到兩個問題。
首先是分數沒有增加。 您應該在外循環中初始化一個計數器,並在遍歷鍵中的項時對其進行遞增。
for val in raw.values():
score = 0
for i in val:
...
score += 1 # or 2 or 4
第二個問題是在存儲分數時,您需要訪問要分數的特定鍵。 由於“ raw.keys()”返回所有鍵的列表,因此在存儲值時使用它是沒有意義的。 相反,您的外循環應遍歷鍵和值,從而使您知道當前使用的鍵。
for key, val in raw.items():
....
總結一下,這是一個工作示例:
score = {}
for key, val in raw.items(): # iterating over both key and value (.items instead of .values)
cur_score = 0 # initializing the current score counter
for item in val: # use readable names!
item_len = len(item) # calculated once for efficiency
if 4 <= item_len < 9: # the python way to check value in range
cur_score += 1
elif 10 <= item_len < 15:
cur_score += 2
else:
cur_score += 3
score[key] = cur_score
玩得開心!
您試圖將整個鍵列表用作字典的索引。 另外,您可以將該分配放入兩個循環中。 您期望在每次迭代中該做什么?
首先,您的外循環必須遍歷字典元素列表,而不僅僅是值。 您將需要以下內容:
for key, val in raw.iteritems():
接下來,您需要維護各個字符串的總得分。 您應該看一下...但是基本思想是
total = 0
for item in my_list: # you have to determine what my_list should be
sc = # score for that item
total += sc
...最后,在此循環之后...
score[key] = total
那應該使您前進。
您需要遍歷字典的所有鍵,值對,並維護字典值(在您的情況下為列表)中每個元素的得分總和。
您可以按以下方式修改代碼以獲取所需的輸出。
raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}
score = {}
# iterating through all the key, value pairs of the dictionary
for key, value in raw.items():
sc = 0
# iterating through all the elements of the current value
for item in value:
if len(item) >=4 and len(item) <=9:
sc += 1
elif len(item) >=10 and len(item) <=15:
sc += 2
else:
sc += 3
score[key] = sc
print(score)
它輸出:
{'id1': 3, 'id2': 2}
因此, for key, value in raw.items():
的循環將for key, value in raw.items():
運行for key, value in raw.items():
為字典的每個鍵值對運行,分別為'id1': ['KKKK', 'MMMMMMMMMMMMMMM']
和'id2': ['KKKKM', 'KKKKKK']
。
然后, for item in value:
的嵌套循環for item in value:
對兩個字典鍵的值['KKKK', 'MMMMMMMMMMMMMMM']
和['KKKKM', 'KKKKKK']
運行兩次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.