1 回答
TA贡献1943条经验 获得超7个赞
我想循环遍历值列表。如果有一个值大于3,则在该值大于或等于1时选择后面的所有值(或者在它降到低于1之前停止)。列表中的其余值应为零,直到列表中的另一个值大于 3 并且该过程会重复进行。
示例:
如果我有以下列表:
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]
到目前为止,我设法获得所有大于 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列表我会使用一个标志来控制允许哪些值通过。另外,我会使用生成器:
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
添加回答
举报