筛选字符串列表

2024-09-27 19:18:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python代码可以执行以下操作:

  1. 读取文件
  2. 转换成字典
  3. 筛选字典中的某些参数

这就是字典的类型:

{'ID1':['100,Cat','100,Cat1','100,Cat2','100,Cat3','99.4,Dog','99.4,Dog1','99.4,Dog3','100,Cat5','100,Cat6']}

现在我必须过滤字典中的值:

1-Filter according to the %: so I fix the first value of the % which in this case is 100 with a margin of 0.05. According to this, I would get

['100,Cat','100,Cat1','100,Cat2','100,Cat3']

所以我做了以下代码:

for keys_ID in dictionary.keys():
    list_2 = []
    list_ID = []
    treshold = dictionary[keys_ID][0].split(',')[0]
    for thre in dictionary[keys_ID]:
        thre_split_ID = thre.split(',')[0]
        thre_split_species = thre.split(',')[1].rstrip('\n')
        if float(thre_split_ID) >= float(treshold) - 0.05 and float(thre_split_ID) <= float(treshold) + 0.05:
            if thre_split_species not in list_2:
                list_2 .append(thre_split_species )
                list_ID.append(thre_split_ID)

但是,此代码为我提供了以下输出:

['100,Cat','100,Cat1','100,Cat2','100,Cat3','100,Cat5','100,Cat6']

在本例中,代码返回具有相同百分比的值

这是所需的输出:['100,Cat','100,Cat1','100,Cat2','100,Cat3']

有人能告诉我怎样才能得到第一个相同的结果吗?谢谢


Tags: the代码iniddictionary字典keysfloat
1条回答
网友
1楼 · 发布于 2024-09-27 19:18:16

按照我对这个问题的理解,您正在寻找第一个值的0.5范围内的值,直到找到一个不同的值。为此,您可以在if条件中添加一个else: break来检查阈值以停止循环

或者,您可以使用例如itertools.takewhile

from itertools import takewhile

val = lambda x: float(x.split(",")[0])
dictionary = {'ID1':['100,Cat','100,Cat1','100,Cat2','100,Cat3','99.4,Dog','99.4,Dog1','99.4,Dog3','100,Cat5','100,Cat6']}
for ID in dictionary.keys():
    first, *rest = dictionary[ID]
    filtered = [first, *takewhile(lambda x: abs(val(first) - val(x)) < 0.5, rest)]
    print(filtered)

输出:

['100,Cat', '100,Cat1', '100,Cat2', '100,Cat3']

相关问题 更多 >

    热门问题