我正在尝试检查字符串是否在字典的其中一个键中.
if message in a_dict: # this will only work if message is exactly one of the keys
#do stuff
Run Code Online (Sandbox Code Playgroud)
我希望条件返回,True即使message它只是其中一个a_dict键的一部分.
我该怎么办?有没有办法.*在字符串中添加正则表达式?或者,还有更好的方法?
你可以使用any:
elif any(message in key for key in a_dict):
do_something()
Run Code Online (Sandbox Code Playgroud)
如果您还需要包含消息的密钥:
else:
key = next((message in key for key in a_dict), None)
if key is not None:
do_something(key)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |