我有list_astring_tmp个这样的

list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'

我想知道list_a中有没有string_tmp个项目,如果有,是type = L1还是type = 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,所以我需要102

# 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))

Output:

L1

Python相关问答推荐

Django注释:将时差转换为小数或小数

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

Python主进程和分支进程如何共享gc信息?

更改Seaborn条形图中的x轴日期时间限制

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何记录脚本输出

如何让Flask 中的请求标签发挥作用

Python库:可选地支持numpy类型,而不依赖于numpy

Python中绕y轴曲线的旋转

如何在给定的条件下使numpy数组的计算速度最快?

如何获得每个组的时间戳差异?

使用密钥字典重新配置嵌套字典密钥名

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

无法连接到Keycloat服务器

matplotlib图中的复杂箭头形状

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

使用__json__的 pyramid 在客户端返回意外格式

Python 3试图访问在线程调用中实例化的类的对象

计算机找不到已安装的库'