簡體   English   中英

如何在列表中的正數之后打印第一個負數?

[英]How can I print first negative number after a positive number in a list?

我想在 python 列表中的正數之后打印第一個負數。 但我無法做到這一點

lst = [2,4,-4,-5,-7,2,3,5,6,-9,-4,-6,3,45,6,-67,-45,-56]

在這個列表中我只想打印 -4,-9,-67

嘗試:

lst = [2, 4, -4, -5, -7, 2, 3, 5, 6, -9, -4, -6, 3, 45, 6, -67, -45, -56]

out = [b for a, b in zip(lst, lst[1:]) if a > 0 and b < 0]
print(out)

印刷:

[-4, -9, -67]

使用 Python 3.10+:

from itertools import pairwise

for a, b in pairwise(lst):
    if a > 0 > b:
        print(b)

沒有:

a = 0
for b in lst:
    if a > 0 > b:
        print(b)
    a = b

你可以這樣做:

for c, item in enumerate(lst): # go through all of the items and their indexs
    if item < 0 and c > 0 and lst[c - 1] >= 0: # check if the previous item is positive and the current number is negative
        print(item) # print the current item

@Andrej Kesely 的一點修改答案,不產生切片列表(通過使用索引代替)你可以獲得相同的結果

out = [lst[i + 1] for i in range(len(lst) - 1) if lst[i] > 0 and lst[i + 1] < 0]

# [-4, -9, -67]

注意:您尚未指定列表中0的正確方法,這可能會稍微改變答案。

最干凈的方法可能是:

[b for a,b in zip(lst, lst[1:]) if a > 0 > b]

(但是對於大型列表來說效率不是很高,因為它會復制列表)

一種更有效的方法可能是:

[lst[i] for i in range(1, len(lst)) if lst[i - 1] > 0 > lst[i]]

(但它不那么優雅)

如果您還需要更高的內存效率,則始終可以使用迭代器(...)而不是列表推導[...]

暫無
暫無

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

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