如何循环检查列表中的所有值是否大于另一个列表中的值?



如问题所示,我如何做一个循环来检查列表中的所有值是否大于另一个列表中的另一组值?假设每个列表的长度相同,并且每个值将根据其索引与另一个值进行比较。

例如:

aList=[1,5,10,15,23]
bList=[0,4,9,14,22]
for x in range(len(aList)):
if aList[x]>bList[x]:
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

这是我现在拥有的,但是由于循环,我最终打印了5次。我只希望结果打印一次。有人知道怎么解决这个问题吗?

使用allzip

if all(a > b for a, b in zip(aList, bList)):
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

使用numpy:

import numpy 
if np.all(np.array(aList) > np.array(bList)):
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

采用您已经完成的方法,只需设置一个标志变量,并在循环后检查标志并打印结果。下面是

的实现
aList=[1,5,10,15,23]
bList=[0,4,9,14,22]
for x in range(len(aList)):
if aList[x] < bList[x]:
flag = True
break
if flag:
print('bList is bigger')
else:
print('aList is bigger')

您只需要对您的代码做一个小的调整。不是在每个元素上打印,而是检查条件,并在结束时根据布尔变量的值打印,本例中的eachGreater

aList=[1,5,10,15,23]
bList=[0,4,9,14,22]
eachGreater = True
for x in range(len(aList)):
if aList[x]>bList[x]:
pass
else:
eachGreater = False
break
if eachGreater:
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

试试这个:

aList=[1,5,10,15,23]
bList=[0,4,9,14,22]
aisbigger=True
for x in aList:
for y in bList:
if(x<y):
aisbigger=False
if(aisbigger):
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

编辑后:如果我没有错,你想比较每个元素只与相同的索引元素在另一个列表。然后试试这个:

aList=[1,5,10,15,23]
bList=[0,4,9,14,22]
aisbigger=True
for x in range(len(aList)):
if(aList[x]<bList[x]):
aisbigger=False
if(aisbigger):
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

Numpy方法使用模块greater_equal

a=[1,5,10,15,23]
b=[0,4,9,14,22]
#Approach 1
if np.greater_equal(a,b).all():
print("All values in aList are bigger than bList")
else:
print("Not all values in aList are bigger than bList")

会给你

list中的所有值都大于bList

重新运行a=[1,5,10,15,20]的代码将得到

不是list中所有的值都大于list

这是最直接的解决方案。这是一个小的改编,从你已经有。

def each_item_larger(a, b):
for pos in range(len(a)):
if (a[pos] < b[pos]):
return False
return True
aList = [1, 5, 10, 15, 23]
bList = [0, 4, 9, 14, 22]
if each_item_larger(aList, bList):
print(“Each item is larger.”)
else:
print(“At least one item is smaller.”)

这是我的实现:

isGreater = True
for x in range(len(aList)):
if aList[x]<bList[x]:
isGreater = False
break
if isGreater:
print("List A is greater than List B")
else:
print("List A is not greater than List B")

相关内容

  • 没有找到相关文章

最新更新