【问题标题】:Checking if element is in tuple using if condition [duplicate]使用 if 条件检查元素是否在元组中
【发布时间】:2016-10-20 14:41:54
【问题描述】:

我正在尝试使用 if 语句检查我的元组中是否有某个数字,但发现很难。这里有什么问题?

def racaman(x):
    y = x
    w = (0,)
    for i in range(y):
        k = w[i]-x[i]
        if k == i in w:
            w = w + ((w[i]+x[i]),)
        else:
            w = w + ((w[i]-x[i]),)

【问题讨论】:

  • 请缩进你的代码...这不可读
  • 只是element in tuple。我不知道你为什么有一个 equals 声明
  • 请提出一个更具体的问题,并说明您尝试过的方法以及遇到的问题。

标签: python tuples


【解决方案1】:

你可以在if条件中替换3来查找特定的数字

def raceman(x):
    #assuming x is tuple
    if 3 in x:
        print("found")
    else:
        print("not found")
raceman((1,2,3,4))

【讨论】:

    【解决方案2】:

    请更正您的问题,正确粘贴代码。 我不确定你在问什么,但我猜:

    tupl = (1,2,3,4,5)
       if 1 in tupl:
           print('y')
       else:
           print('n')
    

    【讨论】:

      【解决方案3】:

      我会推荐一个列表来代替

      def racaman(x):
          w = [0]
          for i in range(x):
              k = w[i]-x[i]
              if k in w:  # fix this 
                  w.append(w[i]+x[i])
              else:
                  w.append(k)  # already calculated 
          return w # did you want to return that? 
      

      【讨论】:

        【解决方案4】:

        这可能只是像这样检查的问题:

        >>>n in t
        

        其中n是数字,t是元组,例如:

        >>>2 in (1,2,3)
        True
        

        但是,如果您正在寻找一个数字并且元素是字符串,这还不够:

        >>>2 in ('a1','a2','a3') #won't return desired output since digit '2' is part of a string
        False
        

        如果是这样,您将需要采用更具适应性的方法,迭代元组的元素并使用适当的正则表达式测试每个元素(@987654324 @)。

        【讨论】:

          猜你喜欢
          • 2021-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-20
          • 2018-02-23
          • 2014-06-28
          • 1970-01-01
          • 2020-08-12
          相关资源
          最近更新 更多