首页 > 解决方案 > 如何检查值是否存在于列表中,元素内用行分隔

问题描述

我需要检查值(例如13or 17.5)是否存在于字符串列表中定义的范围内,例如:

L = ["12-14", "15-16", "17-20"]

例如,范围是12to 14inclusive、15to16等。

我想:

if "13.5" in L:
    print("yes")
else:
    print("no")

预期输出:yes

我怎样才能做到这一点?

标签: pythonlist

解决方案


使用.split(),然后使用与列表中的项目进行比较any

lst = ["12-14", "15-16", "17-20"]

if any(int(i.split('-')[0]) < 13.5 < int(i.split('-')[1]) for i in lst):
    print('yes')
else:
    print('no')
# yes

推荐阅读