python - 如何比较元组列表?
问题描述
我正在尝试将元组列表中的第二个值与下一个第二个值进行比较,依此类推,然后返回 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
推荐阅读
- java - Mockito:如何模拟具有特定属性值的对象
- flutter - 颤振倒数计时器插件不起作用,试图将其设置为我自己的时间但不起作用
- angular - 如何让 Angular 编译器知道 npm/cordova 插件添加的类型定义?
- mysql - Mariadb 10.4 带有 pam_winbind.so 身份验证。得到 ERROR 1045 (28000): Access denied ... (使用密码:否)
- python-3.x - 在 Python 3 中导入 Simpy
- react-testing-library - i18n addResourceBundle 模拟显示错误 i18n 未定义
- excel - 从两个或多个不同的工作表创建一个图表
- docker - 为 Windows 10、32 位安装 Docker
- excel - 如何格式化单元格以使匹配功能适用于该数据集中的所有数字?
- asp.net - IdentityServer4 授权错误与重定向 URI 不匹配