有沒有一種更優雅的方法來檢測串列中的值是否為負數,然后為正數?
例如[-1, 0, -2, 2]回傳True,因為-1是負的,并且2的索引高于-1的索引。
[1, 2, 3, 2]回傳False,因為所有的值都是正的。
[-1, -2, -3, -4]回傳False,因為所有的值都是負數。
[4, 3, 2, 1, -1]回傳 False。
這是我目前的代碼:
def my_function(my_list)。
neg_index = None。
for index, item in enumerate(my_list)。
if item < 0:
neg_index = index
if item > 0:
pos_index = index
if neg_index is not None:
if pos_index > neg_index:
return Truereturn False
uj5u.com熱心網友回復:
你可以使用itertools.groupby:
from itertools import groupby
def positive_follows(lst)。
# 獲得一個起始負值的標記。
prev = False 負值的標記
for key, _ in groupby(lst, lambda x: x < 0)。)
# 如果發現一個負值,就翻轉標記。
# 并轉到下一個組。
if key:
prev = key
繼續
# 如果沒有找到標記,那么我們從開始。
# 一個正值,所以回傳False。
if not prev:
return False[/span
else:
# otherwise return True else: 拒絕接受。
return True
# 如果我們只遇到負值,那么for回圈就會
# 將完成,我們應該回傳False。
else。
return False.
x = [-1, 0, -2, 2] # True # True
assert positive_follows(x)
x = [1, 2, 3, 2] # False]。
assert not positive_follows(x)
x = [- 1, - 2, - 3, - 4] # False # False
assert not positive_follows(x)
uj5u.com熱心網友回復:
你可以使用zip來處理元素和它們的繼承者:
def negThenPos(L)。
L = list(filter(None,L) # ignore zeroes
return any(a<0 and b> 0 for a,b in zip(L,L[1: ]))
print(negThenPos([-1, 0, -2, 2]) # 真
print(negThenPos([1, 2, 3, 2]) # False(假的)。
print(negThenPos([-1, -2, -3, -4] )) # False(假的)。
print(negThenPos([4, 3, 2, 1, -1]) # False[/span
uj5u.com熱心網友回復:
你可以直接回圈瀏覽串列,比如
a = [1, 2, 3, 4]
def Search()。
foundNeg = False[/span
for element in a:
if element < 0:
foundNeg = True :.
if foundNeg:
if element > 0:
return False
print(Search())
這不是一個Pythonic的方法,但它可以完美地作業,其時間復雜度最差也是O(n)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/325735.html
標籤:
