我只想删除列表的最大和最小副本 数字。示例:( 1 1 1 4 4 5 6 8 8 8 )结果:( 1 4 4 5 6 的 8 )
如何将max()min()函数与list(set(x))
组合?
还是有另一种方式吗?
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print average
答案 0 :(得分:0)
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
# numbers = [1, 1, 1, 4, 4, 5, 6, 8, 8, 8]
mi = min(numbers)
ma = max(numbers)
b = [mi] + [x for x in numbers if x != mi and x != ma] + [ma]
答案 1 :(得分:0)
以下是使用某些itertools
函数解决问题的一般方法。该解决方案会将重复的最小值和最大值重叠为单个值,只要重复出现在哪里:
from itertools import groupby,starmap,chain
#first we count the sequence length for each group of number in the list
c=[[number,len(list(seq))] for number,seq in groupby(numbers)]
print(c)
#we collapse the repetitions only for min and max
for group in c:
if group[0] == min(numbers) or group[0]== max(numbers):
group[1]=1
print(c)
#we put back the list together
numbers=list(chain(*starmap(lambda x,n : [x]*n, c)))
print(numbers)
示例输出:
>>>numbers=[1,1,1,4,4,5,6,8,8,8]
[1, 4, 4, 5, 6, 8]
>>>numbers=[4,4,1,1,1,5,6,8,8,8]
[4, 4, 1, 5, 6, 8]
#edge case if there are multiple groups of min :
>>>numbers=[4,4,1,1,1,5,1,1,1,6,8,8,8]
[4, 4, 1, 5, 1, 6, 8]