给出一个数字列表。
lst=[1,1,2,4,8,2]
找到唯一最小值
理想情况下,答案应该是4,但是如何达到4?
答案 0 :(得分:0)
这是一种方法。
例如:
lst=[1,1,2,4,8,2]
print(min([i for i in set(lst) if lst.count(i) == 1]))
# --> 4
答案 1 :(得分:0)
基本上,您首先要对列表进行排序。然后从最低点开始检查计数是否==1。如果计数!= 1继续检查,直到找到“唯一”数字。
def get_lowest_and_unique(lst):
for x in sorted(list(set(lst))):
if lst.count(x) == 1:
return x
print("Could not find the correct element!")
答案 2 :(得分:0)
我会说最好的选择是使用collections.Counter
:
from collections import Counter
lst=[1,1,2,4,8,2]
c = Counter(lst)
min(v for v, n in c.items() if n == 1)
4
答案 3 :(得分:0)
这是使用收藏中的 Counter 函数解决问题的另一种方法。
from collections import Counter
input_list = [1,1,2,4,8,2]
result_dictionary = {key: value for key, value in Counter(input_list).items() if value == 1}
unique_minimum_value = (min(result_dictionary, key=result_dictionary.get))
print (unique_minimum_value)
# output
4
# one line shorter
unique_minimum_value = min({key: value for key, value in Counter(input_list).items() if value == 1})
print (unique_minimum_value)
# output
4
答案 4 :(得分:-1)
尝试
t = list(set(lst))
list.sort(t)
unique_min = t[0]