我想在 python 串列中的正數之后列印第一個負數。但我無法做到這一點
lst = [2,4,-4,-5,-7,2,3,5,6,-9,-4,-6,3,45,6,-67,-45,-56]
在這個串列中我只想列印 -4,-9,-67
uj5u.com熱心網友回復:
嘗試:
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]
uj5u.com熱心網友回復:
你可以這樣做:
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
uj5u.com熱心網友回復:
@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]
uj5u.com熱心網友回復:
使用 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
uj5u.com熱心網友回復:
注意:您尚未指定0串列中對 a 的正確方法,這可能會稍微改變答案。
最干凈的方法可能是:
[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]]
(但它不那么優雅)
如果您還需要更高的記憶體效率,則始終可以使用迭代器(...)而不是串列推導。[...]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/482806.html
上一篇:嵌套for回圈的串列索引超出范圍
下一篇:R:如何洗掉字串中的第n個字符?
