简体   繁体   English

在Python中不按顺序遍历列表

[英]Looping through a list not in order in Python

I am very new to programming, so please bear with me...I have been learning Python and I just did an assessment that involved looping through a list using your current value as the next index value to go to while looping. 我对编程非常陌生,所以请忍受...我一直在学习Python,我刚刚进行了一项评估,涉及使用当前值作为循环时要使用的下一个索引值来循环遍历列表。 This is roughly what the question was: 这大概就是问题所在:

You have a zero-indexed array length N of positive and negative integers. 您有一个正整数和负整数的零索引数组长度N。 Write a function that loops through the list, creates a new list, and returns the length of the new list. 编写一个遍历列表,创建新列表并返回新列表长度的函数。 While looping through the list, you use your current value as the next index value to go to. 遍历列表时,将当前值用作下一个索引值。 It stops looping when A[i] = -1 当A [i] = -1时,它停止循环

For example: 例如:

A[0] = 1
A[1] = 4
A[2] = -1
A[3] = 3
A[4] = 2 

This would create: 这将创建:

newlist = [1, 4, 2, -1]

len(newlist) = 4

It was timed and I was not able to finish, but this is what I came up with. 时间到了,我无法完成,但这就是我想到的。 Any criticism is appreciated. 任何批评表示赞赏。 Like I said I am new and trying to learn. 就像我说的,我是新人,正在尝试学习。 In the meantime, I will keep looking. 同时,我会继续寻找。 Thanks in advance! 提前致谢!

def sol(A):
    i = 0
    newlist = []
    for A[i] in range(len(A)):
        e = A[i]
        newlist.append(e)
        i == e
        if A[i] == -1:
            return len(newlist)

This might be the easiest way to do it if your looking for the least lines of code to write. 如果您要寻找最少的代码行,这可能是最简单的方法。

A = [1,4,-1,3,2]
B = []

n = 0

while A[n] != -1:
    B.append(A[n])
    n = A[n]

B.append(-1)

print(len(B))

First of all, note that for A[i] in range(len(A)) is a pattern you certainly want to avoid, as it is an obscure construct that will modify the list A by storing increasing integers into A[i] . 首先,请注意, for A[i] in range(len(A))中的for A[i] in range(len(A))您肯定要避免使用这种模式,因为它是一种模糊的构造,它将通过将递增的整数存储到A[i]中来修改列表A To loop over elements of A , use for val in A . 要遍历A元素,请在A中使用for val in A To loop over indices into A , use for ind in xrange(len(A)) . 要将索引循环到A ,请使用for ind in xrange(len(A))

The for loop, normally the preferred Python looping construct, is not the right tool for this problem because the problem requires iterating over the sequence in an unpredictable order mandated by the contents of the sequence. for循环,通常是首选的Python循环构造,不是解决此问题的正确工具,因为该问题要求以序列内容所要求的不可预测的顺序遍历序列。 For this, you need to use the more general while loop and manage the list index yourself. 为此,您需要使用更通用的while循环并自己管理列表索引。 Here is an example: 这是一个例子:

def extract(l):
    newlist = []
    ind = 0
    while l[ind] != -1:
        newlist.append(l[ind])
        ind = l[ind]
    newlist.append(-1)   # the problem requires the trailing -1
    print newlist        # for debugging
    return len(newlist)

>>> extract([1, 4, -1, 3, 2])
[1, 4, 2, -1]
4

Note that collecting the values into the new list doesn't really make sense in any kind of real-world scenario because the list is not visible outside the function in any way. 请注意,在任何实际情况下,将值收集到新列表中实际上都没有意义,因为该列表以任何方式在函数外部均不可见。 A more sensible implementation would simply increment a counter in each loop pass and return the value of the counter. 一个更明智的实现方式是在每个循环遍历中简单地增加一个计数器,然后返回计数器的值。 But since the problem explicitly requests maintaining the list, code like the above will have to do. 但是由于问题明确要求维护列表,因此必须执行上述代码。

It's simpler to just use a while loop: 使用while循环更简单:

data = [1,4,-1,3,2]
ls = []
i = 0
steps = 0
while data[i] != -1:
    ls.append(data[i])
    i = data[i]
    steps += 1
    assert steps < len(data), "Infinite loop detected"
ls.append(-1)
print ls, len(ls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM