如果它在列表中,则将 true 分配给变量?

Assign true to a variable if it is in a list?

aBool = bool(aList.index(aVal))

我试过了,但它给出了错误信息。感谢您的帮助!

aVal in aList

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

aList = [10, 20, 30, 40, 50]
aVal = 50
bool = aVal in aList
print bool

有多种方法可以解决此问题,但最简单的方法是使用带有 '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

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

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

您可以将任何值传递给第一个参数,将任何列表传递给第二个参数,如果值在给定列表内,它总是 return 为真(就像您想要的那样,return否则为假)。

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

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

aTest = aVal in aList