【问题标题】:How do I filter a specific number in python?How do I filter a specific number in python?
【发布时间】:2022-12-01 20:57:10
【问题描述】:

current code:

list = [1,2,3,4,5]

for i in list:
    Dev.step(2)
    if i == 2 or 1 or 0:
        Dev.turnLeft()
        Dev.step(Dev.x-Item[i].x)
        Dev.step(Dev.x-15)
        Dev.turnRight()
    else:
        Dev.turnRight()
        Dev.step(Item[i].x-Dev.x)
        Dev.step(15-Dev.x)
        Dev.turnLeft()

How do I create an if statement for the Dev / Character do something for a specific list element or filter the list elements. Example I want, if the number of 'i' is equal to 2 or 1 or 0 the Dev will turnLeft. So the output of the list is seperated with the other numbers.

Example: [2,1,0] and [4,5]

Create an if statement for a specific list elements / numbers.

【问题讨论】:

标签: python


【解决方案1】:

The condition below should represent this:

if i in {0, 1, 2}:
    #do logic

【讨论】:

    【解决方案2】:

    You have to rewrite i for every condition you are evaluating:

    list = [1,2,3,4,5]
    
    for i in list:
        Dev.step(2)
        if i == 2 or i == 1 or i == 0:
            Dev.turnLeft()
            Dev.step(Dev.x-Item[i].x)
            Dev.step(Dev.x-15)
            Dev.turnRight()
        else:
            Dev.turnRight()
            Dev.step(Item[i].x-Dev.x)
            Dev.step(15-Dev.x)
            Dev.turnLeft()
    

    【讨论】:

      【解决方案3】:

      Your if statement won't work because of i == 2 or 1 or 0. See, when you use or, it checks if each statement is true. So you need to use i == for each number. (If this is a bit confusing, feel free to read more about this here)
      You should replace it to:

      if i == 2 or i == 1 or i == 0:
      

      Full code:

      list = [1,2,3,4,5]
      
      for i in list:
          Dev.step(2)
          if i == 2 or i == 1 or i == 0:
              Dev.turnLeft()
              Dev.step(Dev.x-Item[i].x)
              Dev.step(Dev.x-15)
              Dev.turnRight()
          else:
              Dev.turnRight()
              Dev.step(Item[i].x-Dev.x)
              Dev.step(15-Dev.x)
              Dev.turnLeft()
      

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 2022-01-04
        • 2022-12-27
        • 2022-12-01
        • 2022-12-02
        • 2022-12-01
        • 2022-08-17
        • 2022-12-02
        • 2022-12-01
        相关资源
        最近更新 更多