简体   繁体   中英

How to print the items with the number less than 9, and number greater than 10?

I am writing a program to visualize the items in a list that are smaller than or greater than 9. This is the list I have made:

list = [("item1",12.5),("item",2.3),("item",7.0)]

I want to be able to print the items with the number less than 9, and then print those with a number greater than 10.

You can use list comprehensions , which provide a simple way to filter lists:

l = [("item1",12.5),("item",2.3),("item",7.0)]
[i for i in l if i[1] > 9]
# [('item1', 12.5)]

Which is equivalent to the following for loop:

new_list = []
for i in l:
    if i[1] > 9:
        new_list.append(i)
print(new_list)
# [('item1', 12.5)]

Or for values smaller than 9 :

[i for i in l if i[1] < 9]
# [('item', 2.3), ('item', 7.0)]

Given a list,

L = [("item1",12.5),("item",2.3),("item",7.0)]

(note avoiding using the keyword list as a variable name), you can do a list comprehension, for example:

>>> [(item, value) for (item, value) in L if value < 9.0]
[('item', 2.3), ('item', 7.0)]

To change the criteria, change the I f at the end.

Loop/iterate over items in the list

my_list = [("item1",12.5),("item",2.3),("item",7.0)]

for item in my_list:
    if item[1] < 9:  # change <9 to whatever condition you want
        print(item)  

You could use filter function as such:

original_list = [("item1",12.5),("item",2.3),("item",7.0)]

filtered_list = list(filter(lambda x: x[1] < 9.0, original_list))

printing this:

print(filtered_list)

[('item', 2.3), ('item', 7.0)]
liste = [("item1",12.5),("item",2.3),("item",7.0)]
index=0

while(index<liste.__len__()):
   if liste[index][1] > 9:
      print(liste[index])
   index=index+1

Storing the values in 2 lists

my_list = [("item1",12.5),("item",2.3),("item",7.0)]

less_than_9 = [x for x in my_list if x[1] < 9]
more_than_9 = [x for x in my_list if x[1] > 9]

>>> print(less_than_9)
[("item1",12.5)]
>>> print(more_than_9)
[("item",2.3),("item",7.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.

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