繁体   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