Python在列表中搜索在列表中搜索

2024-04-18 07:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么下面的代码不起作用?你知道吗

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]?你知道吗


Tags: 代码in元素列表forsearchdataif
3条回答

使用generator expressions^{}内置函数很容易做到这一点:

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")

列表在Python中是0索引的,因此["4", "5"][1]"5",而不是"4"。你知道吗

另外,您想检查"4"是在子列表中,还是在子列表的第一个位置?如果是前者,您可能希望改用if search in sublist。你知道吗

注意,正如Noctua在注释中提到的,您将只检查这里的第一个子列表,因为在任何情况下都是break,所以您可能希望删除该语句,至少在else分支中。你知道吗

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

相关问题 更多 >