Stagg - 11 months ago 27

Python Question

I need to run through a list of tuples like this:

`list = [('Abraham', 'Lisboa', 42195, '10-18', 2224),`

('Mike', 'Nova Iorque', 42195, '06-13', 2319),

('Abraham', 'Toquio', 42195, '02-22', 2403),

('Mike', 'Sao Paulo', 21098, '04-12', 1182),

('Abraham', 'Sao Paulo', 21098, '04-12', 1096),

('Dora', 'Toquio', 42195, '02-22', 2449),

('Abraham', 'Boston', 42195, '04-20', 2187)]

My function (participations) needs to run through these tuples and count how many times does the first element of the tuples occurrs in general.

For example:

`participations(list)`

>>>[4, 1, 2]

4 is the number of times that the element "Abraham" occurs, 1 is the number of times the element "Dora" occurs and 2 is the number of times the element "Mike" occurs.

The participations in the final list must be in alphabetical order, following the names given.

Here is what I have so far:

`def participations(list):`

result = []

for i in list:

for name in i[0]:

result.append(name)

return result

But it's not giving me what I want, it only gives me the names with every letter separated from each other...

Feel free to ask any questions if you don't understand mine.

Hope you guys can help me, thanks in advance.

Answer

No imports - just one line of list incomprehension :)

```
lst = [('Abraham', 'Lisboa', 42195, '10-18', 2224),
('Mike', 'Nova Iorque', 42195, '06-13', 2319),
('Abraham', 'Toquio', 42195, '02-22', 2403),
('Mike', 'Sao Paulo', 21098, '04-12', 1182),
('Abraham', 'Sao Paulo', 21098, '04-12', 1096),
('Dora', 'Toquio', 42195, '02-22', 2449),
('Abraham', 'Boston', 42195, '04-20', 2187)]
[[y[0] for y in lst].count(z) for z in sorted(set([t[0] for t in lst]))]
```

Python 2.7.6 interpreter:

```
>>> [[y[0] for y in lst].count(z) for z in sorted(set([t[0] for t in lst]))]
[4, 1, 2]
>>>
```

If you want to count the number of occurrences of the first element in the *entire* tuple (as opposed to only considering the first element):

```
[[x for y in lst for x in y].count(z) for z in sorted(set([t[0] for t in lst]))]
```