我有 list_a
和 string_tmp
像这样
list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'
我想知道list_a
中是否有string_tmp
项,如果有,type = L1
else 类型 = L2
?
# for example
type = ''
for k in string_tmp.split():
if k in list_a:
type = 'L1'
if len(type) == 0:
type = 'L2'
这是真正的问题,但在我的项目中,len(list_a) = 200,000
和 len(strgin_tmp) = 10,000
,所以我需要将其设为 超快
# this is the output of the example
type = 'L1'
最佳答案
将引用列表和字符串标记转换为集应该可以提高性能。像这样的事情:
list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'
def get_type(s, r): # s is the string, r is the reference list
s = set(s.split())
r = set(r)
return 'L1' if any(map(lambda x: x in r, s)) else 'L2'
print(get_type(string_tmp, list_a))
输出:
L1
关于python - 如何使用 lambda 在 for 循环内创建 if ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72421637/