首页 > 解决方案 > 如何将字符串与模式“Foo-Bar”匹配,其中 Bar 可以是列表的任何元素?

问题描述

我有一个字符串 L 的列表。

我需要检查一个字符串是直接是 L 的元素还是采用以下格式:“foo-element_of_L”

在 python 中,有没有比为 L 中的所有 X 添加“foo-X”到 L 更好的方法?

标签: pythonpython-3.xpython-2.7

解决方案


我会做两个查找:

if x in L or f'foo-{x}' in L:

这可能比

if any(x == y or f'foo-{x}' == y for x in L):

这基本上就是你所提议的。


推荐阅读