簡體   English   中英

如果新附加的 integer 的值小於該列表中最大的 integer,如何清除列表中的所有整數

[英]How to clear all the integers in a list if the new appended integer has a smaller value than the largest integer of that list

所以我最初有一個整數列表:

Lst=[10,5,8]

當我輸入 append 和 integer 時說 4 我希望列表是這樣的:

Lst=[4]

由於數字 4 小於先前的最大值 (10),因此刪除了所有先前的整數。

同樣,如果我 append 一個不同的值,如 12,列表應該變成[4,12]但我不知道如何 append 並同時刪除整數我應該如何編碼呢?

你可以使用這個 function

def func(l, n):# l is the list, n is the number
    prev_max = max(l)# previous max value
    if n > prev_max:
        l = [n]
    else:
        l.append(n)
    return l
elem = 4 if max(lst) < elem: lst = [elem] else: lst.append(elem)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM