簡體   English   中英

從列表中刪除浮點數和其他小於 n 的數字

[英]Erasing Floats and other numbers less than n from a list

我有一個整數/浮點數列表,下面有一個 for 循環,其目標是從列表中刪除所有小於 1000 的數字。

percentages = [2000, 10, 69.29]

for percentage in percentages:
    if percentage < 1000:
        print("PASS")
        n = percentages.index(percentage)
        del percentages[n]

    if percentage >= 1000:
        print("Qualified")

print(percentages)

但是,十進制數字將被完全忽略。 我究竟做錯了什么?

您可以在不使用顯式循環的情況下過濾列表。

percentages = [2000, 10, 69.29]
percentages = filter(lambda x: x > 1000, percentages)
percentages = list(percentages)

print(percentages)

嘗試列表理解 -

percentages = [2000, 10, 69.29]

percentages = [i for i in percentages if i > 1000]

print(percentages)

嘗試這個:

percentages = [2000, 10, 69.29]

newPercentages = []
for percentage in percentages:
    if percentage < 810:
        pass

    if percentage >= 810:
        newPercentages.append(percentage)

print(newPercentages)

這會將所有內容附加到一個新列表中,但我認為這很好

您可以將數字添加到列表理解中,同時使用必要的條件過濾它們。

percentages = [2000, 10, 69.29]
print([n for n in percentages if n > 1000 or type(n) is not float])

出現此行為的原因是您在遍歷列表時從列表中刪除了一個元素。 嘗試在 for 循環中打印列表,您將了解其行為。 試試這個給出正確結果的代碼。

percentages = [2000, 10, 69.29, 70]
out = []

for percentage in percentages:
    if percentage < 1000:
        print("PASS") 
    if percentage >= 1000:
        print("Qualified")
        out.append(percentage)

print(out)

Output:

Qualified
PASS
PASS
PASS
[2000]

使用,

percentages = [2000, 10, 69.29]
percentages = [i for i in percentages if i > 1000]

列表壓縮只是編寫 for 循環的一種簡短且更有效的方法。 如果我大於 1000, i會被附加到列表中。所以它基本上過濾列表中低於 1000 的所有內容

暫無
暫無

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

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