1

这段代码给了我一个错误,我如何检查变量是否在列表中?

TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]

if KateMarks in myList:
    print("yes")
else:
    print("no")
4

7 回答 7

3

如果 Python 首先不知道某物是什么,它就无法检查某物是否在列表中。(通常,如果您尝试引用尚未定义的变量,则会出现错误。)

在您的示例中,即使您定义myList = [TomMarks, JackMarks]了 ,如果您打印列表,您也会得到:

[[66, 54, 34, 79], [66, 54, 34, 79]]

如果您KateMarks事先定义,那么是的,代码将完美运行。但如果变量未定义,Python 将不知道要检查什么。

于 2013-04-15T03:04:01.887 回答
3

您需要在使用它之前定义一个变量。你告诉编译器“KateMarks”,它不知道它是什么——你认为它会怎么做?

这个:

TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]

KateMarks = 1

if KateMarks in myList:
    print("yes")
else:
    print("no")

工作正常并打印“否”。

您可能想要的是首先检查变量是否存在:

if 'KateMarks' in locals():
于 2013-04-15T03:04:30.553 回答
1

您可以通过字典来代替列表,如下所示:

myList = {'TomMarks':[66,54,34,79], 'JackMarks':[66,54,34,79]}

if 'KateMarks' in myList:
    print("yes")
else:
    print("no")
于 2013-04-15T03:19:09.983 回答
1

如果您真的想打印no即使KateMarks未定义,您可以执行以下操作,但这不是一个好方法。

TomMarks = [66,54,34,79]
JackMarks = [66,54,34,79]
myList = [TomMarks, JackMarks]

try:
    if KateMarks in myList:
        print 'yes'
    else:
        print 'no'
except(NameError):
    print 'no'
于 2013-04-15T03:10:19.223 回答
1

Python 变量名是对对象的引用。因为 KateMarks 没有引用任何东西,所以 Python 会引发 NameError 异常。

命名空间内省可以通过locals()dir()

'KateMarks' in dir()
于 2013-04-15T03:11:00.840 回答
0

Do you mean you're writing some sort of code where you'll get Kate's marks somewhere else in the program, and then check if the marks are in it?

Or actually, on second thought I think the whole list-in-a-list and marks idea is just a distraction... you really mean to ask if you can use a variable name in a similar fashion to a string, right? If that's the case, there's a somewhat not-so-efficient way to do what I think you're trying to do, using dict:

marks = {} # a Python dictionary
marks["Tom"] = 1234123412512352345
marks["Jack"] = 2394872394857389578935

if "Kate" in marks:
    print("Kate is a key in marks.")
else:
    print("Kate isn't a key, but at least now we know that we didn't get Kate's marks.")
于 2013-04-15T03:32:53.810 回答
0

If variable is undefined you just simply check if it is undefined. No undefined variables can be in any list:

if not 'undefined_variable' in dir():
   print "NO WAY!"
于 2013-04-15T03:43:59.157 回答