[英]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.