简体   繁体   English

如何在列表中找到匹配条件的第一个元素?

[英]How to find first elements in list that match a condition?

Say I have a list, l , which contains [5, 10, 15, 16, 20] .假设我有一个列表l ,其中包含[5, 10, 15, 16, 20] I want to get the first elements that are all divisible by 5 (so the first three elements), without the last 20 .我想获得所有可以被5整除的第一个元素(所以前三个元素),而不是最后一个20 How do I do this?我该怎么做呢? I've done:我已经搞定了:

done = False
i = 0
while not done and i < len(l):
    if l[i] % 5 == 0:
        answer.append(source[i])
    else:
        done = True
    i += 1

However, this seems inefficient.但是,这似乎效率低下。 Is there any better way to do this?有没有更好的方法来做到这一点?

The itertools.takewhile function seems like what you want: itertools.takewhile function 似乎是您想要的:

from itertools import takewhile
list(takewhile(lambda x: x % 5 == 0, [5, 10, 15, 16, 20]))

This returns [5, 10, 15] .这将返回[5, 10, 15]

Your idea is actually an efficient answer because it avoids processing more elements than needed.您的想法实际上是一个有效的答案,因为它避免了处理比需要更多的元素。 @SamEstep's answer should be the accepted answer because it uses itertools exactly as intended, but regardless, the correct setup for your code would be the following: @SamEstep 的答案应该是公认的答案,因为它完全按照预期使用itertools ,但无论如何,您的代码的正确设置如下:

l = [5, 10, 15, 16, 20]
result = []
for elem in l:
    if elem % 5 == 0:
        result.append(elem)
    else:
        break
# [5, 10, 15]

Control Structures控制结构

As a side note: a while loop that just indexes a list is discouraged, because it makes your intentions less explicit, and it makes your code more prone to bugs, as you have to handle the indexing yourself.附带说明:不鼓励仅索引列表的while循环,因为它会使您的意图不那么明确,并且会使您的代码更容易出现错误,因为您必须自己处理索引。 A better way to write it would be to write:编写它的更好方法是编写:

for i in range(len(l)):

which gives you an index for each element in the list.它为您提供列表中每个元素的索引。 However, if all you're going to do is index the list, then you can just iterate through each item in the list, which adds readability (this is what I've done above):但是,如果您要做的只是索引列表,那么您可以遍历列表中的每个项目,这增加了可读性(这就是我在上面所做的):

for elem in l:

If you need both the index and the element, use enumerate :如果您需要索引元素请使用enumerate

for idx, elem in enumerate(l):

This will make your code more readable, and less bug-prone.这将使您的代码更具可读性,并且不易出错。

in the else code block just use break will be fineelse代码块中使用break就可以了

Say you have myList and you want to find items in it that can be divided by n:假设您有 myList,并且您想在其中找到可以除以 n 的项目:

myList = [1,2,10,12,5,20]
ansList = []
ansCount = 0
for i in myList:
    if i % n == 0:
        # condition is true, do whaterver you want with "i"; here I added it to a new list(ansList)
        ansList.append(i)
        ansCount += 1
        # you can also break the loop as your wish
        if ansCount > 2:
            break

It's not really inefficient, but probably a clearer way would be -这并不是真的低效,但可能更清晰的方法是 -

l = [5, 10, 15, 16, 20]
result = []
for item in l:
    if item % 5 == 0:
        result.append(item)
    else:
        break

this gives [5, 10, 15]这给出了 [5, 10, 15]

you can use something like this你可以使用这样的东西

mylist = [5, 10, 15, 16, 20]
result = []
for item in mylist:
    if item % 5 != 0:
        break
    result.append(item)
print(result)

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

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