1 回答

TA貢獻1943條經(jīng)驗 獲得超7個贊
我想循環(huán)遍歷值列表。如果有一個值大于3,則在該值大于或等于1時選擇后面的所有值(或者在它降到低于1之前停止)。列表中的其余值應(yīng)為零,直到列表中的另一個值大于 3 并且該過程會重復(fù)進行。
示例:
如果我有以下列表:
l = [1, 3, 2, 3, 2, 4, 1, 3, 5, 6, 7, 6, 7, 8, 1, 0, 1, 2, 1, 3, 4, 7, 8, 9, 7, 5, 2, 1, 2, 4, 7, 8, 1, 3]
我想得到以下信息:
o = [0, 0, 0, 0, 0, 4, 1, 0, 5, 6, 7, 6, 7, 8, 1, 0, 0, 0, 0, 0, 4, 7, 8, 9, 7, 5, 2, 1, 0, 4, 7, 8, 1, 0]
到目前為止,我設(shè)法獲得所有大于 3 的值,其余為 0,但我不知道如何整合其他條件:
l = [1, 3, 2, 3, 2, 4, 1, 3, 5, 6, 7, 6, 7, 8, 1, 0, 1, 2, 1, 3, 4, 7, 8, 9, 7, 5, 2, 1, 2, 4, 7, 8, 1, 3]
o = [0] * len(l)
for index in range(len(l)):
if l[index] > 3:
o[index] = l[index]
else:
o[index] = 0
輸出:
[0, 0, 0, 0, 0, 4, 0, 0, 5, 6, 7, 6, 7, 8, 0, 0, 0, 0, 0, 0, 4, 7, 8, 9, 7, 5, 0, 0, 0, 4, 7, 8, 0, 0]
Python列表我會使用一個標(biāo)志來控制允許哪些值通過。另外,我會使用生成器:
def a_filter(items, on=3, off=1):
through = False
for item in items:
if item > on:
through = True
elif item < off:
through = False
yield item if through else 0
if item <= off:
through = False
l = [1, 3, 2, 3, 2, 4, 1, 3, 5, 6, 7, 6, 7, 8, 1, 0, 1, 2, 1, 3, 4, 7, 8, 9, 7, 5, 2, 1, 2, 4, 7, 8, 1, 3]
o = [0, 0, 0, 0, 0, 4, 1, 0, 5, 6, 7, 6, 7, 8, 1, 0, 0, 0, 0, 0, 4, 7, 8, 9, 7, 5, 2, 1, 0, 4, 7, 8, 1, 0]
print(l)
# [1, 3, 2, 3, 2, 4, 1, 3, 5, 6, 7, 6, 7, 8, 1, 0, 1, 2, 1, 3, 4, 7, 8, 9, 7, 5, 2, 1, 2, 4, 7, 8, 1, 3]
print(o)
# [0, 0, 0, 0, 0, 4, 1, 0, 5, 6, 7, 6, 7, 8, 1, 0, 0, 0, 0, 0, 4, 7, 8, 9, 7, 5, 2, 1, 0, 4, 7, 8, 1, 0]
print(list(a_filter(l)))
# [0, 0, 0, 0, 0, 4, 1, 0, 5, 6, 7, 6, 7, 8, 1, 0, 0, 0, 0, 0, 4, 7, 8, 9, 7, 5, 2, 1, 0, 4, 7, 8, 1, 0]
print(o == list(a_filter(l)))
# True
添加回答
舉報