如何按大小对包含字符串和整数的列表进行排序,然后在python 3中输出整数或字符串

问题描述 投票:-1回答:1

我有这段代码,它将对输入进行排序,但是它唯一起作用的方法是在将输入输入列表之前对输入进行排序。我想重新编写代码以获取任何列表并输出单词或数字,以第二大为准。

def secound_largest(values: {}):
    sorted_values = sorted(values.items(), key=lambda kv: kv[1], reverse=True)
    second_maximum = list(sorted_values)[1][0]
    print(str(second_maximum)+ 'is the second largest item on the list')

if __name__ == '__main__':
    list_input_amount = int(input('How many items are in your list? '))
    dictonary_values = {}
    for amount in range(list_input_amount):
        list_input = input('Please enter your list item: ')
        if list_input.isnumeric():
            dictonary_values[int(list_input)] = int(list_input)
        else:
            dictonary_values[list_input] = len(list_input)

    secound_largest(dictonary_values)
python sorting
1个回答
0
投票

以下代码将满足您的要求:

def argmax(subscriptable):
    _max = subscriptable[0]
    _max_inv = 0
    for idx in range(1, len(subscriptable)):
        elem = subscriptable[idx]
        if elem > _max:
            _max = elem
            _max_inv = idx
    return _max_inv

def second_large_arg(subscriptable):
    big1 = subscriptable[0]
    big2 = subscriptable[1]
    big1_inv = 0
    big2_inv = 1
    if big1 < subscriptable[1]:
        big1 = subscriptable[1]
        big2 = subscriptable[0]
        big1_inv = 1
        big2_inv = 0
    for idx in range(2, len(subscriptable)):
        elem = subscriptable[idx]
        if elem > big1:
            big2_inv = big1_inv
            big1 = elem
            big1_inv = idx
        elif elem > big2:
            big2 = elem
            big2_inv = idx
    return big2_inv

d = {
    0:23,
    1:83,
    2:999999999999999999999999999999,
    3:87,
    4:91,
    5:32111111,
    6:21
}
print(argmax(d)) # prints 2
print(second_large_arg(d)) # prints 5

L = {
    0:"apple",
    1:1,
    2:"SUBDERMATOGLYPHIC",
    3:"banana",
    4:99999999999999,
    5:2
}

L = [len(x) if hasattr(x, "__len__") else x for x in L.values()]

print(L)

print(argmax(L))  # prints 4
print(second_large_arg(L))  # prints 2
© www.soinside.com 2019 - 2024. All rights reserved.