帮助解决我的python LIST问题?

时间:2009-10-07 03:15:21

标签: python

author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]

author_A AND author_B = ['book_z',3,30]
             author_A = [['book_x',1,10],['book_y',2,20]]
             author_B = [['book_s',5,10],['book_t',2,20]]
             ---------------------------------------------

我想要这样的现有数据

     author     quantity   Amount($)
      A&B        3            30
      A          3            30
      B          7            30
      total      13           90

我不想要像这样的现有数据!在这种情况下,它是ADDED副本['book_z',3,30]

         author   quantity   Amount($)
          A         6            60
          B         10           60
          total     16           120

这是我的问题,任何人请帮助我解决这个问题。  谢谢大家

3 个答案:

答案 0 :(得分:6)

author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]

def present(A, B):
  Aset = set(tuple(x) for x in A)
  Bset = set(tuple(x) for x in B)
  both = Aset & Bset
  justA = Aset - both
  justB = Bset - both
  totals = [0, 0]
  print "%-12s %-12s %12s" % ('author', 'quantity', 'Amount($)')
  for subset, name in zip((both, justA, justB), ('A*B', 'A', 'B')):
    tq = sum(x[1] for x in subset)
    ta = sum(x[2] for x in subset)
    totals[0] += tq
    totals[1] += ta
    print ' %-11s  %-11d    %-11d' % (name, tq, ta)
  print ' %-11s  %-11d    %-11d' % ('total', totals[0], totals[1])

present(author_A, author_B)

我试图用一些数字左对齐和完全时髦的间距重现你想要的奇怪格式,但我确定你需要调整各种打印语句中的格式才能得到确切的(并且非常奇怪) )示例的格式化效果。但是,除了输出的间距和左右对齐外,这应该完全符合您的要求。

答案 1 :(得分:1)

你可以找到这样的交叉点和独家......

A_and_B = [a for a in author_A if a in author_B]
only_A = [a for a in author_A if a not in author_B]
only_B = [b for b in author_B if b not in author_A]

然后只是印刷它们的问题......

print '%s %d %d' % tuple(A_and_B)
print '%s %d %d' % tuple(only_A)
print '%s %d %d' % tuple(only_B)

希望有所帮助

答案 2 :(得分:0)

books = {
    'A':[['book_x',1,10],['book_y',2,20]],
    'B':[['book_s',5,10],['book_t',2,20]],
    'A & B':[['book_z',3,30]],
}
for key in books:
    quantity = []
    amount = []
    for item in books[key]:
        quantity.append(item[1])
        amount.append(item[2])
    print ("%s\t%s\t%s") % (key,sum(quantity),sum(amount))