簡體   English   中英

返回列表中小於其索引的第一個整數的索引

[英]Returning the index of the first integer in a list that is less than its index

我是 python 的初學者,我不知道如何做到這一點。
有人知道我如何修復我的代碼嗎?

def smaller_index(items: list[int]) -> int:
    """
    Return the index of the first integer in items that is less than its index,
    or -1 if no such integer exists in items.
    
    >>> smaller_index([2, 5, 7, 99, 6])
    -1
    >>> smaller_index([-5, 8, 9, 16])
    0
    >>> smaller_index([5, 8, 9, 0, 1, 3])
    3
    """
    min_value = min(items)
    if items.count(min_value) > 1:
            return [i for i, x in enumerate(items) if x == min(items)]
    else:
           return items.index(min(items))

這是此問題的解決方案。

def smaller_index(items: list) -> int:
    """
    Return the index of the first integer in items that is less than its index,
    or -1 if no such integer exists in items.

    #>>> smaller_index([2, 5, 7, 99, 6])
    -1
    #>>> smaller_index([-5, 8, 9, 16])
    0
    #>>> smaller_index([5, 8, 9, 0, 1, 3])
    3
    """
    for i in range(len(items)):
        if items[i] < i:
            return i
    return -1

print(smaller_index([5, 8, 9, 0, 1, 3]))

邏輯分解:

  • 我將項目指示的數據類型從 list[int] 更改為 list - 由於某種原因,這表示錯誤(需要進一步調查)
  • 使用元素的索引遍歷列表 - 比較它們,如果滿足條件,則返回索引的值。
  • 如果元素中沒有元素滿足你的條件,for循環完成后,返回-1
def smaller_index(items: list) -> int:
    for i, n in enumerate(items):
        if n < i:
            return i
    return -1

假設我理解你想要做什么,這可以像你想要的那樣簡單。

快樂編碼!

暫無
暫無

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

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