有三个列表
list=[1.2,1.3,1.4]
list1=[4.5,5.6,6.5]
list2=[5.5,7.5,7.2,]
如何用循环语句判断列表1值在1-2之间有多少个,列表2值在4-5之间的有多少个,列表3值在5-6之间的有多少个
print(len([i for i in list if 1<=x<=2]))
print(len([i for i in list1 if 4<=x<=5]))
print(len([i for i in list2 if 5<=x<=6]))
你题目的解答代码如下:
list1=[1.2,1.3,1.4]
list2=[4.5,5.6,6.5]
list3=[5.5,7.5,7.2]
print(len(list(filter(lambda x: 1<=x<=2, list1))))
print(len(list(filter(lambda x: 4<=x<=5, list2))))
print(len(list(filter(lambda x: 6<=x<=7, list3))))
或者
list1=[1.2,1.3,1.4]
list2=[4.5,5.6,6.5]
list3=[5.5,7.5,7.2]
print(len([x for x in list1 if 1<=x<=2]))
print(len([x for x in list2 if 4<=x<=5]))
print(len([x for x in list3 if 6<=x<=7]))
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
在列表解析式中使用for循环,用sum函数汇总满足条件的个数。代码如下:
list1=[1.2,1.3,1.4]
list2=[4.5,5.6,6.5]
list3=[5.5,7.5,7.2]
a=sum([True for x in list1 if 1<=x<=2])
b=sum([True for x in list2 if 4<=x<=5])
c=sum([True for x in list3 if 5<=x<=6])
print(a,b,c)
如有帮助,请点采纳。