[英]python-Check if all elements in list1 are greater than eliments of the same index in list2
我有两个清单:
x = [50,25,30]
y = [25,30,50]
我是编程新手,如何使用循环或其他函数确定x [0]> = y [0],x [1]> = x [1]?
我想避免简单的事情:
x[0] >= y[0]
x[1] >= y[1]
x[2] >= y[2]
因为这些列表可能会附加。
我将您的列表分别重命名为list1
和list2
:
result = all(x >= y for x, y in zip(list1, list2))
这里all(iterable)
检查的所有元素是否iterable
是“truthy”。
我的解决方案将基于每个列表的长度相同的事实。
if len(x) == len(y):
test_container = 0 #will store the number of trues
for i in range(len(x)):
if x[i] > y[i]:
test_container += 1
if test_container == len(x):
print("All elements in x are bigger than the correspondent in y")
else:
print("False")
result = True
for xi, yi in zip(x, y):
if xi < yi:
result = False
break
结果将包含答案。
如果您想将其用作功能:
def compare(x, y):
for xi, yi in zip(x, y):
if xi < yi:
return False
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.