简体   繁体   中英

getting second smallest value from list

x = [[1,2,3,4],[4,5,0,1],[22,21,31,10]]


def minFor(x):

    removingvalue = []    

    for i in x:
        minvalue = i[0]

        for j in i:           
            if j < minvalue:
                minvalue=j

        for i in range(0,len(x)):
            if x==minvalue:
                removingvalue = removingvalue + minvalue
            return minvalue

        print(minvalue)

what I 'm trying to do here is first find the smallest number from the list. And remove that smallest value and find again the smallest number from the list. But the remove function doesn't work

This finds second smallest of each sublists in the list:

lst = [[1,2,3,4],[4,5,0,1],[22,21,31,10]] 

print([sorted(x)[1] for x in lst])
# [2, 1, 21]

You just needed to sort sublist in ascending order and select second value out. There is no need of removing value from list.

Personally, I'd use the builtin sorted function:

def second_min(x):
    result = []
    for sublist in x:
        result.extend(sublist)
    # this flattens the sublists
    # into a single list
    result = sorted(result)
    return result[1]
    # return the second element

And without the built-ins, replace the sorted() call with:

...
for i in range(len(result) - 1):
    if result[i] > result[i + 1]:
        result[i:i + 2] = [result[i + 1], result[i]]
...

要查找每个子列表的最小值,您可以执行以下操作:

min_values = [min(sub_list) for sub_list in x]

Use min(iterable) and a list comprehension to get the overall minimal value.

Then use min on the same list comp with a twist: only allow values in the second list comp that are bigger then your minimal min-value:

xxxx = [[1,2,3,4],[4,5,0,1],[22,21,31,10]]

minmin = min((x for y in xxxx for x in y)) # flattening list comp
secmin = min((x for y in xxxx for x in y if x >minmin))

print(minmin,secmin)

Output:

0 1

You can convert the given data-structure, to a single list and then sort the list. The first two elements give you the answer you want. Here's what you can do:

input_list = x
new_l = []
for sl in input_list:
    new_l.extend(sl)
new_l.sort()

# First two elements of new_l are the ones that you want.
remove_smallest = [sorted(i)[1:] for i in x]
get_smallest = [min(i) for i in remove_smallest]

print(remove_smallest)
print(get_smallest)
 [[2, 3, 4], [1, 4, 5], [21, 22, 31]] [2, 1, 21] 

Expanded loops:

remove_smallest = []
for i in x:
    remove_smallest.append(sorted(i)[1:])

get_smallest = []
for i in remove_smallest:
    get_smallest.append(min(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM