我有两个元组列表:
old = [('6.454', '11.274', '14')]
new = [(6.2845306, 11.30587, 13.3138)]
我想比较同一位置的每个值(6.454
与6.2845306
等等),如果old
元组的值大于new
的值1}}元组,我打印它。
那应该是净效应:
6.454, 14
我是使用简单的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个元素的元组,所以在这里使用切片并不是一个大问题,但我正在寻找更优雅的解决方案,即列表理解。谢谢你的帮助。
答案 0 :(得分:2)
所以你想要这样的东西:
print [o for o,n in zip(old[0],new[0]) if float(o) > float(n)]
答案 1 :(得分:2)
使用内置函数zip
:
for x,y in zip(old[0],new[0]):
if float(x)>float(y):
print x,
....:
6.454 14
如果元组长度不等,那么zip
只会比较两者中的较短者,你可以使用itertools.izip_longest
来处理这种情况
zip
上的帮助:
In [90]: zip?
Type: builtin_function_or_method
String Form:<built-in function zip>
Namespace: Python builtin
Docstring:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
答案 2 :(得分:2)
[o for o,n in zip(old[0], new[0]) if float(o) > float(n)]
这应该有用吗?
答案 3 :(得分:1)
试试这个:
for i in range(len(old)):
for j in range(len(old[i]):
if old[i][j]>new[i][j]:
print old[i][j]