Domanda

cardPayments={}
rowNumber, NumOfCardPayments = 0, len(cardPayments)

for x in range(5):
    cardPayments.update({x:x})
    print(cardPayments)
    print('cardPayments: '+str(NumOfCardPayments)+'\n')

Output:

{0: 0}
cardPayments: 0

{0: 0, 1: 1}
cardPayments: 0

{0: 0, 1: 1, 2: 2}
cardPayments: 0

{0: 0, 1: 1, 2: 2, 3: 3}
cardPayments: 0

{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
cardPayments: 0

I was hoping that by referencing NumOfCardPayments to len(cardPayments) that as cardPayments dict increased in size so would the int value of NumOfCardPayments during the for loop, this seems to not be the case.

How can I create NumOfCardPayments as a variable which is maintained as a reference of len(cardPayments)?

(Please note, I would not like to simply do NumOfCardPayments+=1 within the for loop)

È stato utile?

Soluzione

The closest thing that comes to mind is a property, which automatically evaluates a function when read:

>>> class LenDict(dict):
...   @property
...   def len(self):
...     return len(self)
...
>>> d=LenDict()
>>> d.len
0
>>> d[1]=2
>>> d.len
1
>>>

But IMHO this is no clearer than using len(d) directly, and certainly not as efficient. It's also possible to place the hook the other way around by wrapping setitem.

Altri suggerimenti

I don't think it is possible. In Python, variables contain pointers to objects. Integer objects are immutable. Therefore, the only way to change the value of numOfCardPayments is to bind it to a new object...

You could make a simple lambda object to return the length of a specific object

def len_follower(target_object):
    return lambda : len(target_object)

Then set the parameter target_object as cardPayments

>>>cardPayments = {}
>>>NumOfCardPayments = len_follower(cardPayments)
>>>NumOfCardPayments()
0
>>>cardPayments[1] = 0
>>>NumOfCardPayments()
1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top