【问题标题】:Assign true to a variable if it is in a list?如果变量在列表中,则为变量赋值?
【发布时间】:2015-08-11 19:53:54
【问题描述】:
aBool = bool(aList.index(aVal))

我试过这个,但它给出了一个错误的错误。任何帮助表示赞赏!

【问题讨论】:

标签: python list boolean


【解决方案1】:
aVal in aList

如果我理解正确,in 运算符可以满足您的需求。

【讨论】:

  • 如果 aVal 和 aList 对象之间存在大小写差异怎么办
  • 如果它们是两者之间的大小写差异,它仍然会给出 False 结果。 aList = ['a',2,3,4,'e'] aVal = 'A' aBool = bool(aVal in aList) 。我希望这能清楚地解释你的疑问
  • 'a' in ['A'] 将按预期给出 False。
【解决方案2】:
aList = [10, 20, 30, 40, 50]
aVal = 50
bool = aVal in aList
print bool

【讨论】:

    【解决方案3】:

    有不同的方法可以解决这个问题,但最简单的方法是使用带有“in”运算符的条件。例如,

    #testbool will hold your boolean value
    #testlist will be your list
    #testvar will be your variable you are checking the list for
    
    if testvar in testlist:
        testbool = true
    else:
        testbool = false
    

    【讨论】:

    • 我强烈建议您将代码简化为:testbool = testvar in testlist。不需要if ... else 声明。
    【解决方案4】:

    这是一个通用的解决方案:

    _list = range(10)
    aVal = 7
    aBool = (lambda val, l: True if val in l else False)(aVal, _list)
    print(aBool)
    

    您可以将任何值传递给第一个参数,也可以将任何列表传递给第二个参数,如果值在给定列表内,它将始终返回 True(如您所愿,否则返回 False)。

    【讨论】:

    • 请始终保持您的代码简单 (KISS)!与aBool = aVal in _list相比,附加值是多少? 通用解决方案是什么意思?
    【解决方案5】:

    使用testvar in testlist 将返回一个布尔值。

    如果你想重用这个值,你可以这样做:

    aTest = aVal in aList
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-17
      • 2018-08-14
      • 2022-11-28
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多