列表上的Python无限循环

时间:2017-01-15 18:05:04

标签: python list indexing while-loop

我确信这是一个非常明显的东西,我错过了,但有人可以告诉我为什么这段代码片段会在无限循环中继续吗?

bucket = [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]

def find_index(bucket,keyword):
    index = 0
    for e in bucket:
        while e[0] <> keyword:
            index = index + 1
    return index


print find_index(bucket,'Nick')

2 个答案:

答案 0 :(得分:1)

这个怎么样?
两个for循环可以防止循环无限运行。

bucket = [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]

def find_index(bucket, keyword):
    for index, subArray in enumerate(bucket):
        for element in subArray:
            if element == keyword:
                return index

print find_index(bucket, 'Nick')

答案 1 :(得分:0)

怎么样?

bucket = [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]

def find_index(bucket,keyword):
    index = 0
    for e in bucket:
        while e[index] <> keyword:
            index = index + 1
    return index


print find_index(bucket,'Nick')

您使用了e[0]代替e[index]