【发布时间】:2015-08-01 21:12:35
【问题描述】:
我有两个元组列表
t1 = [ ('a',3,4), ('b',3,4), ('c',4,5) ]
t2 = [ ('a',4,6), ('c',3,4), ('b',3,6), ('d',4,5) ]
这样
- 元组的顺序可能不相同,并且
- 列表可能包含不同数量的元组元素。
我的目标是比较两个列表,如果字符串元素匹配,则比较元组中的最后一个整数元素,如果 t1[2]
我尝试了不同的变体,但我遇到的问题是找到一种方法来匹配字符串以进行正确的比较。
return [diff_unique(x[2],y[2]) for x,y in zip(new_list,old_list) ]
其中 diff_unique 进行上述整数比较,new_list 是 t1,old_list 是 t2。
我也试过这个:
return [diff_unique(x[2],y[2]) for x,y in zip(new_list,old_list) if(x[0]==y[0]]
我打算使用返回的列表并创建一个新的四元组列表,其中包含原始 t1 值以及与匹配 t2 元组的差异。即
inc_dec_list = compare_list(new,old)
final_list = [ (f,r,u,chge) for (f,r,u), chge in zip(new,inc_dec_list)]
其中新 = t1 和旧 = t2。这可能是一个重要的细节,抱歉我错过了。
对正确方向有任何帮助吗?
编辑:我添加了我的测试用例程序,该程序模仿了我对那些想要帮助的人的初衷。谢谢大家。
import os
import sys
old = [('a',10,1),('b',10,2),('c',100,4),('d',200,4),('f',45,2)]
new = [('a',10,2),('c',10,2),('b',100,2),('d',200,6),('e',233,4),('g',45,66)]
def diff_unique(a,b):
print "a:{} = b:{}".format(a,b)
if a < b:
return -1
elif a==b:
return 0
else:
return 1
def compare_list(new_list, old_list):
a = { t[0]:t[1:] for t in new_list }
b = { t[0]:t[1:] for t in old_list }
common = list( set(a.keys())&set(b.keys()))
return [diff_unique(a[key][1], b[key][1]) for key in common]
#get common tuples
#common = [x for x,y in zip(new_list,old_list) if x[0] == y[0] ]
#compare common to old list
#return [diff_unique(x[2],y[2]) for x,y in zip(new_list,old_list) ]
inc_dec_list = compare_list(new,old)
print inc_dec_list
final_list = [ (f,r,u,chge) for (f,r,u), chge in zip(new,inc_dec_list)]
print final_list
【问题讨论】:
-
你能添加预期的输出吗?
-
@BhargavRao 我已经编辑了这篇文章。谢谢