-1

为什么下面的代码不起作用?

data = [["4","5"],["3","7"]]
search = "4"
for sublist in data:
    if sublist[1] == "4":
        print ("there"), sublist
        break
    else:
        print("not there")
        break

非常抱歉给大家带来的困惑。我试图检查整个列表及其所有子列表,但我不明白这只会检查列表的第二个元素,因为我忘记了 Python 的第一个元素位于第 0 个位置。但是,我将如何检查整个列表?删除“break”和[1]?

4

5 回答 5

2

列表在 Python 中是从 0 开始索引的,所以["4", "5"][1]"5",而不是"4"

另外,您是否要检查是否"4"在子列表中,或者在子列表中,在第一个位置?如果是前者,您可能想if search in sublist改用。

请注意,正如 Noctua 在评论中提到的那样,您只会在此处检查第一个子列表,因为break无论如何都是您,因此您可能希望至少在else分支中删除该语句。

于 2013-09-29T17:07:16.450 回答
2

使用生成器表达式any内置函数很容易做到这一点:

data = [["4","5"],["3","7"]]
search = "4"

if any(element == search for sublist in data for element in sublist):
    print ("there")
else:
    print("not there")

甚至更短,正如@Veedrac 在评论中指出的那样:

if any(search in sublist for sublist in data):
    print ("there")
else:
    print("not there")

编辑:如果要打印找到元素的子列表,则必须使用显式循环,如@thefourtheye 的答案所示:

for sublist in data:
    if search in sublist:
        print("there", sublist)
        break
else:
    print("not there")
于 2013-09-29T17:09:06.393 回答
2
data = [["4","5"],["3","7"]]
search = "4"
for sublist in data:
    if search in sublist:
        print ("there", sublist)
        break
else:
    print("not there")
于 2013-09-29T17:11:05.167 回答
0

Thomas 所说的,+ 无论如何你都在破坏,所以在主列表中的第一个元素之后,你只是跳出 for 循环而不检查任何其他元素。你需要的是:

data = [["4","5"],["3","7"]]
search = "4"
for sublist in data:
    if sublist[0] == "4":
        print "there", sublist
        break
else:
    print "not there"  # executed when the for-loop finishes without break
于 2013-09-29T17:09:23.370 回答
0

当你写

if sublist[1] == "4":

您正在检查第二个元素是否为“4”。

要检查是否"4" sublist请使用

if "4" in sublist:

要检查是否"4"在位置 1,请使用

if sublist[0] == "4":

此外,您break在 every 之后else,所以如果第一个没有匹配项,则list不要检查后面的匹配项!删除那个break

于 2013-09-29T17:09:44.413 回答