我试图将元组列表中的第二个值与下一个值进行比较,依此类推,并返回 true,每个值都大于下一个值。例如...
如果前面的每个值都大于下一个值,则返回 True。
968854000 > 957946000 > 878825000 > 810870000 = True
list_of_tuples = [
('2018-09-30', 968854000),
('2017-09-30', 957946000),
('2016-09-30', 878825000),
('2015-09-30', 810870000)]
如果不是则返回 False。
968854000 > 957946000 !> 998825000 stop evaluation and return False
list_of_tuples = [
('2018-09-30', 968854000),
('2017-09-30', 957946000),
('2016-09-30', 998825000),
('2015-09-30', 810870000)]
我已经尝试了以下方法,我觉得我走在正确的轨道上,但无法理解它。
for i, j in enumerate(list_of_tuples):
date = j[0]
value = j[1]
if value > list_of_tuples[i+1][1]:
print(list_of_tuples[i+1][1])
最佳答案
使用这组函数,它们对于测试列表值的单调性非常有用:
def strictly_increasing(L):
return all(x<y for x, y in zip(L, L[1:]))
def strictly_decreasing(L):
return all(x>y for x, y in zip(L, L[1:]))
def non_increasing(L):
return all(x>=y for x, y in zip(L, L[1:]))
def non_decreasing(L):
return all(x<=y for x, y in zip(L, L[1:]))
def monotonic(L):
return non_increasing(L) or non_decreasing(L)
然后隔离元组第二个元素的列表:
list_of_tuples = [
('2018-09-30', 968854000),
('2017-09-30', 957946000),
('2016-09-30', 878825000),
('2015-09-30', 810870000)]
list_to_test = [x[1] for x in list_of_tuples]
non_increasing(list_to_test)
结果:
True
关于python - 如何比较元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56032561/