比较不同元组的值,列表理解

2024-05-20 17:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个元组的列表:

old = [('6.454', '11.274', '14')] 
new = [(6.2845306, 11.30587, 13.3138)]

我想比较同一位置的每个值(6.454与{}等等),如果old元组的值大于new元组的值,我就打印它。在

净效应应为:

^{pr2}$

我用简单的if语句完成了这项工作

if float(old[0][0]) > float(new[0][0]):
    print old[0][0],
if float(old[0][1]) > float(new[0][1]):
    print old[0][1],
if float(old[0][-1]) > float(new[0][-1]):
    print marathon[0][-1]

由于总是有3个或2个元素元组,所以在这里使用切片并不是一个大问题,但我正在寻找更优雅的解决方案,即列表理解。谢谢你的帮助。在


Tags: 元素列表newif切片语句解决方案float
3条回答
[o for o,n in zip(old[0], new[0]) if float(o) > float(n)]

这应该行吗?在

所以你想要这样的东西:

print [o for o,n in zip(old[0],new[0]) if float(o) > float(n)]

使用内置函数zip

for x,y in zip(old[0],new[0]):
    if float(x)>float(y):
        print x,
   ....:         
6.454 14

如果元组的长度不等,zip将只比较两者中较短的一个,可以使用^{}来处理这种情况

关于zip的帮助:

^{pr2}$

相关问题 更多 >