How to assign each variable in the list, number and then add numbers for the same variables?

For example, if you enter ZZAZAAZ, the amount Awill be 14(since its placement is equal 3,5,6), and the amount Zwill be 14 (1 + 2 + 4 + 7).

How should I do it?

+4
source share
3 answers

You can use the generator expression in sum:

>>> s='ZZAZAAZ'
>>> sum(i for i,j in enumerate(s,1) if j=='A')
14
+10
source

For all the elements in syou can do this. In addition, it will find the counts for each element in one pass of the row s, therefore, it will be linear in the number of elements in s.

>>> s = 'ZZAZAAZ'
>>> d = {}
>>> for i, item in enumerate(s):
    ... d[item] = d.get(item, 0) + i + 1
>>> print d
{'A': 14, 'Z': 14}
+1
source

Kasra enumerate, , , , :

>>> s = 'ZZAZAAZ' 
>>> {let:sum(a for a,b in enumerate(s,1) if b==let) for let in set(s)}
{'Z': 14, 'A': 14}
0

All Articles