首页 > python > Python:从列表中的列表中获取最小的项目

Python:从列表中的列表中获取最小的项目 (Python: Get the smallest item from a list inside a list)

2015-11-07 python

问题

假设我有一个名为data的列表。

data = [[3.59, ['foo']], [2.34, ['bar', 'foo']]]

现在我想从数据列表中找到索引,索引0中数据列表中的数字是最小的。所以这将在我的示例0或1中,但因为2.34小于3.59,它将返回1

编辑:

这是我想出来的,但我认为它不是真正有效的atm。

data = [[3.59, ['foo']], [2.34, ['bar', 'foo']]]
smallest_num_list = []

for list in data:
    for i in list[:1]:
        smallest_num_list.append(i)

for list in data:
    for i in list[:1]:
        if i == min(smallest_num_list):
            result = data.index(list)

print result

解决方法

你可以使用enumerate()

idx_min, val_min = min(enumerate(data), key=lambda i, x: x[0])

问题

Let's say I have a list named data.

data = [[3.59, ['foo']], [2.34, ['bar', 'foo']]]

Now I want to find the index from the list in data, wich number in the list inside data at index 0 is the smallest. So that would be in my example 0 or 1 but because 2.34 is less then 3.59 it would return 1

Edit:

This is what i come up with but I don't think it is really efficient atm.

data = [[3.59, ['foo']], [2.34, ['bar', 'foo']]]
smallest_num_list = []

for list in data:
    for i in list[:1]:
        smallest_num_list.append(i)

for list in data:
    for i in list[:1]:
        if i == min(smallest_num_list):
            result = data.index(list)

print result

解决方法

You could use enumerate():

idx_min, val_min = min(enumerate(data), key=lambda i, x: x[0])
相似信息