簡體   English   中英

如何獲取用戶輸入並將其放置在列表中類似元素的旁邊?

[英]How to take user input and place next to similar element in list?

使用 Python 3.8我有一個列表,我正在嘗試向用戶詢問 3 個輸入,例如

list = [7, 5, 3, 2, 2, 1]

獲得 3 個輸入,例如 8、7、3

然后將它們按順序排列,例如[8, 7, 5, 3, 3, 2, 2, 1]

到目前為止,我嘗試如下(只是一個測試),但它在末尾添加了 7,而不是在其他 7 旁邊。我只是很困惑。 我知道我可以使用排序,但這太容易了。

natural = [7, 5, 3, 3, 2]
entry = 7

for item in natural:
    if entry >= item:
        natural.insert(item, entry)
        break

print(natural)

謝謝你的幫助!

您可能需要像這樣定義自己的reverse_insert function :(模擬bisect模塊)

def reverse_insort(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x > a[mid]: hi = mid
        else: lo = mid+1
    a.insert(lo, x)

lst = [7, 5, 3, 3, 2]

x = 7

reverse_insort(lst, x)

print(lst)

Output:

[7, 7, 5, 3, 3, 2]

暫無
暫無

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

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