如何限制 for 循环根据 python 中的值打印列表中的前几个元素?

How to limit for loop to print first few element from list in terms of their value in python?

我想限制 for 循环打印列表中的前几个元素的值。例如,如果我 < 6 :

list = [1,2,3,4,5,6,7,8,9,10]
for i < 6 in list:
    print(i)

提前致谢!

In [9]: L = [1,2,3,4,5,6,7,8,9,10]

In [10]: for i in L:
   ....:     if i<6:
   ....:         print(i)
   ....:         
1
2
3
4
5

基于 我想限制 for 循环根据它们的值打印列表中的前几个元素 看来列表是有序的所以你可以使用 itertools.takewhile

from itertools import takewhile

lst = [1,2,3,4,5,6,7,8,9,10] # don't use list

tke = takewhile(lambda x: x< 6, lst)

for t in tke:
    print(t)
1
2
3
4
5

如果您想要一个列表,请使用 list(...)

print(list(takewhile(lambda x: x< 6, lst))) # good reason why we should not use list as a variable name 
[1, 2, 3, 4, 5]