如果值大于 x,则从列表中选择所有值,直到值大于 y。将所有其他值设为 0

我想循环遍历值列表。如果有一个值大于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]


函数式编程
浏览 101回答 1
1回答

杨__羊羊

我想循环遍历值列表。如果有一个值大于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]&nbsp;o = [0] * len(l)for index in range(len(l)):&nbsp; &nbsp; if l[index] > 3:&nbsp; &nbsp; &nbsp; &nbsp; o[index] = l[index]&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; 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):&nbsp; &nbsp; through = False&nbsp; &nbsp; for item in items:&nbsp; &nbsp; &nbsp; &nbsp; if item > on:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; through = True&nbsp; &nbsp; &nbsp; &nbsp; elif item < off:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; through = False&nbsp; &nbsp; &nbsp; &nbsp; yield item if through else 0&nbsp; &nbsp; &nbsp; &nbsp; if item <= off:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; through = Falsel = [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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python