在Python中将列表中的每两个元组组合在一起

时间:2015-06-10 23:33:34

标签: python

在元组列表中,我试图将每个连续对转换为其总和。

,例如,

>>> def require_alive(func):
...     def wrapper(self, *args, **kwargs):
...         if not self.alive:
...             raise Exception("Not alive")
...         return func(self, *args, **kwargs)
...     return wrapper
...
>>> def require_hungry(func):
...     def wrapper(self, *args, **kwargs):
...         if not self.hungry:
...             print "Not hungry..."
...         else:
...             return func(self, *args, **kwargs)
...     return wrapper
...
>>> class Pet(object):
...     def __init__(self):
...         self.alive = True
...         self.hungry = True
...     def die(self):
...         self.alive = False
...     @require_alive
...     @require_hungry
...     def eat(self):
...         print "Eating..."
...         self.hungry = False
...     @require_alive
...     def sleep(self):
...         print "Sleeping..."
...
>>> roofus = Pet()
>>> roofus.eat()
Eating...
>>> roofus.eat()
Not hungry...
>>> roofus.sleep()
Sleeping...
>>> roofus.die()
>>> roofus.eat()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in wrapper
Exception: Not alive

如何做到这一点?

示例:

[(t1, ), (t2, ), (t3, ), (t4, )] --> [(t1, t2) + (t3, t4)] 

然后输出应为:

 a = [(119, 'Bob', 1L, 1L), (116, 'Twilight Sparkle', 1L, 1L), (117, 'Fluttershy', 0L, 1L), (118, 'Applejack', 0L, 1L)]

1 个答案:

答案 0 :(得分:2)

说清单是:

a = [(1, 2), (3, 4), (5, 6), (7, 8)]

然后使用itertools.izip(对于Python2.7),

import itertools

你可以使用:

>> [aa + bb for (aa, bb) in itertools.izip(a[::2], a[1::2])]

[(1, 2, 3, 4), (5, 6, 7, 8)]