比较两个基于python的元组列表

时间:2017-10-24 06:05:34

标签: python list tuples

尝试根据两个列表中存在的键来比较两个元组列表。我的清单如下所示。

date >= '01-Oct-2017' && date <= '02-Oct-2017' && id==100

考虑第一个元素作为比较的关键,我想要像这样的输出

sr = [('#1', '004634105000', 'sr1'), ('#2', '01fG91258000', 'sr2'), ('#6','01F991259000', 'sr3'), ('#4', '07W997296000', 'sr4'), ('#5', '07W997296000', 'sr5'), ('#7', '454546465666', 'sr6'), ('#7', '4545TRY5666', 'sr7')]

tr = [ ('#1', '00461U105000', 'tr1'), ('#2', '01F991258000', 'tr2'),
('#3', '01F991259000', 'tr3'), ('#4', '07W997296000', 'tr4'),
('#5', '07W997296000', 'tr5'), ('#6', '454546465666', 'tr6')]

这是我尝试的代码,但它没有提供所需的输出

common records:('#1', '004634105000', 'sr1'), ('#1', '00461U105000', 'tr1') ('#2', '01fG91258000', 'sr2'), ('#2', '01F991258000', 'tr2') ('#4', '07W997296000', 'sr4'), ('#4', '07W997296000', 'tr4') ('#5', '07W997296000', 'sr5') , ('#5', '07W997296000', 'tr5')
present only in sr: ('#7', '454546465666', 'sr6'), ('#7', '4545TRY5666', 'sr7')
present only in tr: ('#6', '454546465666', 'tr6')

我在循环中遗漏了一些内容,也没有处理重复内容,如果有人可以帮助我那会很好。谢谢

2 个答案:

答案 0 :(得分:0)

首先,按标准方式按键对数据进行分组:

by_key={}
for xr in (sr,tr):  # cover both lists
  for x in xr:
    by_key.setdefault(x[0], []).append(x)

然后,形成键组:

sk=set(x[0] for x in sr)
tk=set(x[0] for x in tr)

然后解决三个类别:

for nm,keys in (("common records",sk&tk),
                ("present only in sr",sk-tk),
                ("present only in tr",tk-sk)):
  print(nm+':', " ".join(str(x) for k in keys for x in by_key[k]))

答案 1 :(得分:0)

最接近您自己的代码的解决方案是:

sr = [('#1', '004634105000', 'sr1'), ('#2', '01fG91258000', 'sr2'),
      ('#6','01F991259000', 'sr3'), ('#4', '07W997296000', 'sr4'), 
      ('#5', '07W997296000', 'sr5'), ('#7', '454546465666', 'sr6'), 
      ('#7', '4545TRY5666', 'sr7')]

tr = [('#1', '00461U105000', 'tr1'), ('#2', '01F991258000', 'tr2'),
      ('#3', '01F991259000', 'tr3'), ('#4', '07W997296000', 'tr4'),
      ('#5', '07W997296000', 'tr5'), ('#6', '454546465666', 'tr6')]

print ("present only in sr")
source = []
for key in tr:
    source.append(key[0])
for value in sr:
    if value[0] not in source:
        print (value[0], value[1], value[2])

print ("present only in tr")
target = []

for key in sr:
    target.append(key[0])
for value in tr:
    if value[0] not in target:
        print (value[0], value[1], value[2])

print ("common entries")
common = []

for key in sr:
    common.append(key[0])
for value in tr:
    if value[0] in common:
      print (value[0], value[1], value[2])

你缺少的部分是:

source.append(key[0])

key[0]的值添加到源列表中。

你应该考虑使用字典,正如Davis Herring所建议的