问题:找到一个子字符串
为您提供了美国各州及其首都的词典(我的实际名单比下面提供的要大)。词典中的键是状态,值是大写字母。
编写代码以返回所有大写字母的列表,这些大写字母的名称中包含州名作为子字符串。
提示:例如,印第安纳波利斯的大写字母名称和印第安纳州的州名是您的代码将找到的键/值对之一。您的代码应将印第安纳波利斯添加到列表中。找到所有大写字母并将其添加到列表后,请打印出列表。
# Run this cell to create a dictionary of states' capitals
capitals={
'Illinios': 'Springfield',
'Indiana': 'Indianapolis',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
}
我相信我必须使用子字符串或包含。我是Python的新手。非常感谢,谢谢。
capitals={capital:state}
list_of_all_capitals=[]
for capital in state
list_of_all_capitals.append=[capital]
print(list_of_all_capitals)
答案 0 :(得分:0)
使用list-comprehension遍历字典,并使用成员运算符检查子字符串的存在:
[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']