[英]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:我正在编写一个程序来可视化列表中小于或大于 9 的项目。这是我制作的列表:
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.我希望能够打印数字小于 9 的项目,然后打印数字大于 10 的项目。
You can use list comprehensions , which provide a simple way to filter lists:您可以使用list comprehensions ,它提供了一种过滤列表的简单方法:
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:这相当于以下 for 循环:
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
:或者对于小于
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: (注意避免使用关键字
list
作为变量名),您可以进行列表理解,例如:
>>> [(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.要改变标准,改变了
I
在最后F。
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将值存储在 2 个列表中
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.