簡體   English   中英

在字典中查找子字符串; key的值子串; 蟒蛇

[英]Find a substring in a dictionary; value substring of key; Python

問題:查找子字符串

您將獲得美國各州及其首都的字典(我的實際列表比下面提供的更大)。 字典中的鍵是狀態,值是資本名稱。

編寫代碼以返回包含名稱中狀態名稱作為子字符串的所有大寫的列表。

提示:例如,印第安納波利斯作為大寫名稱,印第安納州作為州名稱是您的代碼可以找到的鍵/值對之一。 您的代碼應將Indianapolis添加到列表中。 找到所有大寫並將其添加到列表后,打印出列表。

# Run this cell to create a dictionary of states' capitals

capitals={
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}

我相信我必須使用substring或contains。 我是Python的新手。 我很感激,謝謝。

capitals={capital:state}
list_of_all_capitals=[]
for capital in state
list_of_all_capitals.append=[capital]
print(list_of_all_capitals)

使用list-comprehension迭代字典並使用membership運算符檢查子字符串是否存在:

[y for x, y in capitals.items() if x in y]

代碼中

capitals = {
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}

print([y for x, y in capitals.items() if x in y])
# ['Indianapolis', 'Oklahoma City']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM