我有一个python代码可以执行以下操作:
这就是字典的类型:
{'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']
有人能告诉我怎样才能得到第一个相同的结果吗?谢谢
按照我对这个问题的理解,您正在寻找第一个值的0.5范围内的值,直到找到一个不同的值。为此,您可以在
if
条件中添加一个else: break
来检查阈值以停止循环或者,您可以使用例如
itertools.takewhile
:输出:
相关问题 更多 >
编程相关推荐