简体   繁体   English

打印列表中的元素,直到使用列表推导找到一个元素

[英]print elements from a list until one element is found using list comprehension

so i was doing this exercise from w3schools所以我在 w3schools 做这个练习

  1. Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.编写一个 Python 程序,以相同的顺序打印给定数字列表中的所有偶数,如果序列中 237 之后有任何数字,则停止打印。

and since i read about list comprehension i wanted to put it into practice, and i came to this自从我读到列表理解后,我想把它付诸实践,我来到了这个

numbers = [ 233,12,59,213,69,923,30,10,420,237,432,
           233,98,912,5,61]

print([x for i,x in enumerate(numbers) if i in 
       [i for i,x in enumerate(numbers[:numbers.index(237)])] and x % 2 == 0])

it works but is this the proper way of doing it?它有效,但这是正确的做法吗? is it very ugly?是不是很丑?

Use enumerate and the % operator:使用 enumerate 和 % 运算符:

numbers = [ 233,12,59,213,69,923,30,10,420,237,432,
           233,98,912,5,61]

print([num for idx, num in enumerate(numbers) if num % 2 == 0 and idx < numbers.index(237)])

Output: Output:

[12, 30, 10, 420]
end = numbers.index(237)
print([x for i,x in enumerate(numbers) if x%2==0 and i<end])

You could try this.你可以试试这个。 Replace end with it's value to implement it in a single line.用它的值替换end以在一行中实现它。

Output: Output:

[12, 30, 10, 420]
[x for x in numbers[:numbers.index(237)] if x%2==0]

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

相关问题 使用列表理解从一个列表中减去另一个列表中的元素。 返回不完整列表? - Subtract elements from one list from another list, using list comprehension. Returns incomplete list? 如何在Python中使用list comprehension从一个元素中获取多个元素? - How to get multiple element from one using list comprehension in Python? 尝试使用列表理解打印嵌套列表的第一个元素 - Trying to print the first element of a nested list using list comprehension 使用列表理解打印列表列表 - Print list of list using list comprehension 如何打印列表元素直到到达某个元素 - How to print list elements until a certain element is reached 使用列表推导返回第一个找到的元素或无 - Using a list comprehension for returning first found element or None 使用列表理解从python中的列表字典中提取列表元素 - Extracting list elements from dictionary of lists in python using list comprehension 在列表中加入元素,直到找到某些元素,然后跳过并添加其余元素 - Joining elements in list until certain element is found and skip it and add the rest 使用理解将元素添加到列表 - Adding elements to List using a comprehension python - 如何从第一个元素开始从列表中一个一个打印元素并递增直到最后一个 - How can I print an element from a list one by one starting by first element and increment until the last one in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM