python - 如何使用 lambda 在 for 循环内创建 if ?

标签 python list-comprehension

我有 list_astring_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,000len(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/

相关文章:

python - 价格合适 'Showcase Showdown'

haskell - 非详尽模式异常,用于绑定(bind)但不用于 do

Python 理解随机 float

python - 使用列表理解创建升序和降序数字的一般列表

Python:列表理解中某处出错了?

python - 如何在 Python 中使用具有复杂类型的 C 函数?

python - 基本的python算术——除法

python - 使用 BeautifulSoup 删除 Python 中不需要的标签

python - 更新 google auth2 后 Gspread 保持事件状态

Python:拆分函数是否在列表理解中被多次评估?