简体   繁体   English

如何按大小对具有字符串和整数的列表进行排序,然后 output 在 python 3 中的整数或字符串

[英]How to sort a list that has strings and ints by size then output either int or string in python 3

I have this code, which will sort the inputs, but the only way it works is by the inputs being sorted before they are entered into the list.我有这段代码,它将对输入进行排序,但它的唯一工作方式是在输入进入列表之前对其进行排序。 I want to re write the code to take any list and output the word or number, whichever happens to be second largest.我想重新编写代码以取任何列表和 output 的单词或数字,以第二大为准。

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)

The following code will do what you want:以下代码将执行您想要的操作:

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
list2= [] list= [3, 5, 'python', 2, -1, 7] for i in range(len(list)): try: item=[len(list[i]),list.index(list[i])] list2.append(item) except TypeError: item= [list[i],list.index(list[i])] list2.append(item) list2.sort(key=lambda x:x[0],reverse=True) print(list[list2[1][1]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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