在列表中找到每个嵌套列表的最小值和最大值

时间:2018-11-11 10:24:56

标签: python

我试图在嵌套列表中找到每个列表的最小值和最大值,以及出现最小值或最大值的索引:

因此,例如:

l=[[5,6,7][6,10,9,6][2,3,1]]

成为:

maxl=[7,10,3]
indexl=[2,1,2]

我已经尝试过了,这似乎使我获得了最大列表(尚无索引),但是却没有得到最小化-有人知道如何最好地做到这一点吗?

maxHap=[]
for subL in happiness1:
    maxHap.append(max(subL))
print(maxHap)

minHap=[]
for subL in happiness1:
    minHap.append(min(subL))
print(minHap)

谢谢新手

3 个答案:

答案 0 :(得分:2)

其他选项:

l=[[5,6,7],[6,10,9,6],[2,3,1]]

maxs = [ max(s) for s in l ] #=> [7, 10, 3]
max_idxs = [ s.index(max(s)) for s in l ] #=> [2, 1, 1]
mins = [ min(s) for s in l ] #=> [5, 6, 1]
mins_idxs = [ s.index(min(s)) for s in l ] #=> [0, 0, 2]


或者,您可以将结果存储到一个字典数组中,一个衬里:

mapp = map(lambda x: {'max': max(x), 'max_idxs': x.index(max(x)), 'min': min(x), 'min_idxs': x.index(min(x)) }, l)

for k in mapp:
  print(k)

#=> {'max': 7, 'max_idxs': 2, 'min': 5, 'min_idxs': 0}
#=> {'max': 10, 'max_idxs': 1, 'min': 6, 'min_idxs': 0}
#=> {'max': 3, 'max_idxs': 1, 'min': 1, 'min_idxs': 2}

答案 1 :(得分:1)

您可以使用方法index获取列表值的索引: https://docs.python.org/3/tutorial/datastructures.html

maxl = []
indexl = []
for inner_list in l:
    max_value = max(inner_list)
    maxl.append(max(max_value))
    indexl.append(inner_list.index(max_value)

答案 2 :(得分:1)

您可以使用以下单线:

l=[[5,6,7],[6,10,9,6],[2,3,1]]
maxL, index = zip(*[(max(subList), subList.index(max(subList))) for subList in l])
print(maxL) # will output (7, 10, 3)
print(index) # will output (2, 1, 1)