【问题标题】:Change Value in a list based on previous condition根据先前的条件更改列表中的值
【发布时间】:2021-02-22 20:39:43
【问题描述】:

我有一个零和一的列表。 如果先前的值也是 1 以获得所需的输出,我正在尝试将 1 的值替换为 0,如下所示。

list =     [1,1,1,0,0,0,1,0,1,1,0]
new_list = [1,0,0,0,0,0,1,0,1,0,0]

我尝试使用 for 循环无济于事。有什么建议吗?

【问题讨论】:

  • 你能告诉我们你试过的代码吗?
  • y = np.copy(x); y[1:] = y[1:] & ~y[:-1]
  • @WarrenWeckesser - 太棒了!我试图找出一种按位执行此操作的方法。这应该是公认的答案。感谢您的洞察力。
  • 谢谢!这很好用,可能是最干净的方法。为了变得困难假设我们希望保留前两次出现的 1,因此新输出将是 new_list = [1,1,0,0,0,0,1,1,0]

标签: python list numpy enumerate


【解决方案1】:

这个for循环怎么样:

list =     [1,1,1,0,0,0,1,0,1,1,0]
new_list = []

ant=0
for i in list:
    if ant ==0 and i==1:
        new_list.append(1)
    else:
        new_list.append(0)
    ant=i

【讨论】:

    【解决方案2】:
    question_list = [1,1,1,0,0,0,1,0,1,1,0]
    new_list = [question_list[0]] # notice we put the first element here
    for i in range(1, len(question_list) + 1):
        # check if the current and previous element are 1
        if question_list[i] == 1 and question_list[i - 1] == 1:
            new_list.append(0)
        else:
            new_list.append(question_list[i])
    

    这里的想法是我们遍历列表,同时检查前一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2022-10-13
      相关资源
      最近更新 更多