![](/img/trans.png)
[英]Given a list of [string, number] tuples, create a dictionary where keys are the first characters of strings and the values are sums of the numbers
[英]Matching characters of a string with keys of a dictionary and converting strings to values of keys if matched
我有一本my_dict={'A':1, 'B':1,'C':1,'D':2,'E':2,'F':2,'G':3,'H':3,'I':3}
我想寫一個 function 輸入一個字符串,如果長度為 5,則使用字典的鍵檢查字符串的字符,如果匹配,則打印這些鍵的值, 否則應該返回 false。 例如,如果我輸入一個字符串“ABIFA”,它應該產生 11321。下面是我的代碼,但它沒有產生我期望的結果:
my_dict={'A':1, 'B':1,'C':1,'D':2,'E':2,'F':2,'G':3,'H':3,'I':3}
def string_to_number(mystring):
if len(mystring)==5:
result = [val for key, val in my_dict.items() if mystring in key]
print(str(result))
else:
return False
string_to_number("ABIFA") # should produce 11321
string_to_number("ABIFAA") # should return False
你能告訴我我哪里出錯了嗎?
您可以 map 每個鍵/值結果到str
然后使用生成器表達式join
def string_to_number(mystring):
if len(mystring) == 5:
return ''.join(str(my_dict[i]) for i in mystring)
else:
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.