在字典中获取最大值和最小值

时间:2016-04-12 22:13:52

标签: python dictionary

Illinois: ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3']
Indiana: ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2']

这些在我的字典中为d。 如何获得字典中每个键的最大值和最小值,并获得值为的索引。

例如: 在伊利诺伊州,26是指数5的最大值,3是指数15的最小值。 在印第安纳州:13是最大值,它是指数7,2是最小值,是指数14

输出:

Illinois: 26 in index 5 and 3 in index 15
Indiana: 13 in index 7 and 2 in index 14

我该怎么做?

d = {}
for row in csv_f:
    d[row[0]]=row[1:]

2 个答案:

答案 0 :(得分:0)

有点被抛在一起,但似乎做了这件事。

d = {"Illinois": ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3'],
"Indiana": ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2']}

if __name__ == "__main__":
    print d

    for state in d:
        # returns the numbers with their index (#, index)
        pairs = [(int(d[state][x]), x) for x in xrange(len(d[state]))]
        minpair = min(pairs)
        maxpair = max(pairs)
        print "%s: %d in index %d and %d in index %d"%(state,maxpair[0],maxpair[1],
        minpair[0],minpair[1])

输出:

{'Indiana': ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2'], 'Illinois': ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3']}
Indiana: 13 in index 6 and 2 in index 13
Illinois: 26 in index 4 and 3 in index 14

绕过空白字符串,你可以将列表理解分解为

    pairs = []
    for x in xrange(len(d[state])):
        try:
            pairs.append( (int(d[state][x]), x) )
        except ValueError:
            pass # not a valid number

答案 1 :(得分:0)

这是一个返回dict {country: (maxval, index), (minval, index))}的解决方案:

d = {
    'Illinois': ['13', '12', '18', '23', '26', '25', '24', '19', '13', '10', '15', '14', '14', '4', '3'],
    'Indiana': ['7', '6', '7', '8', '11', '11', '13', '12', '7', '7', '7', '7', '9', '2', '2']
}


maxmin = {}
for state, numbers in d.items():
    maxmin[state] = (
        max(enumerate(numbers), key=lambda x: int(x[1])),
        min(enumerate(numbers), key=lambda x: int(x[1]))
    )


print(maxmin)