【问题标题】:pairwise comparison of integers in list列表中整数的成对比较
【发布时间】:2019-03-25 03:19:38
【问题描述】:

我在这里要做的是比较成对的整数。

如果我有配对列表

[(10, 5), (6, 3), (2, 20), (100, 80)]

我想比较每对的 x > y 如果任何对不满足条件,则返回 False

def function(list_or_tuple):
num_integers = len(list_or_tuple)

pairs_1 = list(zip(list_or_tuple[::2], list_or_tuple[1::2]))
print(pairs_1)
#pairs_2 = list(zip(list_or_tuple[1::2], list_or_tuple[2::2]))
#print(pairs_2)

for x1, y1 in pairs_1:
    return bool(x1 > y1)

对于上面的例子,我的程序继续返回 True

我相信程序只测试第一对,即 (10,5)

我应该怎么做才能让我的程序测试列表中的所有对?

【问题讨论】:

标签: python python-3.x list for-loop


【解决方案1】:

all 函数与列表理解一起使用会更容易:

lst = [(10, 5), (6, 3), (2, 20), (100, 80)]
result = all(x[0] > x[1] for x in lst)

【讨论】:

  • 或任何相反的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
相关资源
最近更新 更多