我想知道是否有人在所有考試中都獲得了 5/5 的滿分,我會將密鑰附加到串列中。
# dictionary could be larger
dicti = {'John': ['5/5', '50/50', '10/10', '10/10']}
liste = []
def f():
for key, value in dicti.items():
count = 0
for i in value:
if i.isdigit(): # kkk
count = 1
if len(value) == count:
liste.append(key)
print(liste)
f()
# I realized in # kkk part doesn't see 5/5 as a digit.
# How can i make this happen?
uj5u.com熱心網友回復:
'5/5'是一個字串,isdigit()如果所有字符都是數字,方法只會回傳 True。這不是因為'/'. 另一方面,Python 不評估字串的內容。它本身就是一個物件!(eval如果您打算這樣做,我不建議使用它來評估該字串)
相反,您可以通過撰寫一個小的輔助函式來檢查自己,該函式也檢查他/她是否獲得了完整的分數:
dicti = {
'John': ['5/5', '50/50', '10/10', '10/10'],
'test_person': ['5/5', '49/50']
}
def is_full(x):
left, right = x.split('/')
return left == right
lst = []
for k, v in dicti.items():
if all(is_full(grade) for grade in v):
lst.append(k)
print(lst)
輸出:
['John']
uj5u.com熱心網友回復:
您應該將字典值中的串列元素寫為字串型別的整數。例如,不要寫“10/10”,而應該寫“1”。所以這將正常作業。
uj5u.com熱心網友回復:
嘗試這個。注意以下代碼會將姓名添加到串列中,即使學生已經獲得了一次滿分。
dicti = {'John': ['5/5', '50/50', '10/10', '10/10']}
fullMarks = ['5/5', '50/50', '10/10', '10/10'];
names = []; # an empty list to add names whose marks are full
def f():
for keys,values in dicti.items():
for value in values: # looping through the value list inside the list
if(value in fullMarks): # if the full marks are in the list (even one time)
names.append(keys); # adding the name into the empty list
break; # don't loop further
f()
print(names);
uj5u.com熱心網友回復:
我認為一個非常優雅的解決方案意味著使用正則運算式:
import re
dicti = {'John': ['5/5', '50/50', '10/10', '10/10'], 'Paul': ['4/5', '50/50', '10/10', '10/10']}
def f():
liste = [key for key, value in dicti.items() if all([re.match("(\d )/\\1", v) for v in value])]
print(liste)
f()
輸出
['John']
基本上,"(\d )/\\1"當斜線前后的數字相同時匹配,即達到滿分,但是你想表達它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375713.html
上一篇:如何使用python檢查給定的英陳述句子是否包含所有無意義的單詞?
下一篇:計算字典鍵出現在資料框中的次數
