對你自己的例子稍作修改應該會給你你想要的。 您的原始示例顯示您不知道迭代字典會爲您提供字典的鍵。 「aproprty_name」+ 1幾乎不會給你你想要的東西。
class IterableObject:
def __iter__(self):
properties = (i for i in self.__dict__)
While True:
a = properties.next()
try:
b = properties.next()
except StopIteration:
yield (getattr(self,a),) #for the odd number of properties case
raise StopIteration
yield getattr(self, a), getattr(self, b)
這不適用於您提供的示例。你不能盲目地預期價值會以任何順序從另一個減去另一個的意義。
你可能想要的是一個對象,它從一個你知道是偶數個值的值列表中返回下一個值。您將不得不在對象中設置該列表。這樣,順序中的配對將以相同的順序傳回。
class PairedList:
def __iter__(self):
balances = iter(self.balances)
while True:
yield balances.next(), balances.next()
>>> b = PairedList()
>>> b.balances = (2000, 151, 1000, 255, 600, 150, 0, 20, 30, 30, 50, 10)
>>> [i for i in b]
[(2000, 151), (1000, 255), (600, 150), (0, 20), (30, 30), (50, 10)]
>>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in b]
[(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)]
你可能想重讀你的問題和榜樣,重新改寫問題,因爲寫你正在創建一個新的對象,並期待它已經包含了你的價值觀。使用我PairedList類,願意爲你做這方面的一個例子是:
>>> PairedList.balances = b.balances
>>> [(balance-withdrawal, balance, withdrawal) for balance, withdrawal in PairedList()]
[(1849, 2000, 151), (745, 1000, 255), (450, 600, 150), (-20, 0, 20), (0, 30, 30), (40, 50, 10)]
但是,這是幾乎可以肯定不是你想要的。它會默認限制你只有一組餘額可以迭代。並且會爲每個PairedList對象創建一個默認的餘額設置,最終會讓您再次陷入困境。
謝謝,但有沒有更簡單的方法來做到這一點,而無需走itertools的路線? – Spikie 2010-04-13 13:23:22