For example, if I wanted to know what numbers are divisible by 2 and had
test_list = [6, 4, 8, 9, 10]
print([number % 2 == 0 for number in test_list])
which would evaluate to:
[True, True, True, False, True]
What can I do to get the elements that evaluate to True in a list? Like this:
[6, 4, 8, 10]
(in python)
How about this?
print([x for x in test_list if x % 2 == 0])
Use list comprehension
print([num for num in test_list if num % 2 == 0])
[6, 4, 8, 10]
Ok, you where very close to the solution. In your list comprehension you told the program to put in the list not number
, the actual member of your list, but number % 2 == 0
, that is of course a bool
type.
To get the list you want, you have to tell the comprehension to get number
from test_list
each time the condition you want is met (in your case that it's even)
print([number for number in test_list if number % 2 == 0])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.