0

I've got this code:

all_sorted = [['9', 's'], ['11', 'h'], ['2', 's'], ['13', 'c'], ['13', 's'], ['11', 's'], ['3', 'd']]
pairness = {str(i): 0 for i in range(14, 1, -1)}
for card in all_sorted:
    pairness[card[0]] += 1

Is it possible to write 2nd-4th lines of code in 1 more efficient line?

Jakub Bielan
  • 575
  • 1
  • 5
  • 14

2 Answers2

3

Shorter, but I don't know how much faster (probably not much, if at all)

>>> from collections import Counter
>>> Counter(x for x, _ in all_sorted)
Counter({'11': 2, '13': 2, '9': 1, '2': 1, '3': 1})
BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • The `map` function is slower than the list comprehension. https://stackoverflow.com/questions/1247486/list-comprehension-vs-map – Attila Bognár Jan 22 '19 at 14:36
  • Not a bad approach, assuming that it's not strictly necessary to display all the keys that have a count of zero. I wouldn't worry about speed, since looping once over a list with ten elements is unlikely to be a performance bottleneck. – Kevin Jan 22 '19 at 14:36
  • Is it possible with list comprehension? – Jakub Bielan Jan 22 '19 at 14:37
  • List comprehensions produce lists, and the result you want is a dict. So no, you can't do this with _just_ a list comprehension. – Kevin Jan 22 '19 at 14:38
1

A version using collections.Counter that creates the keys with zero values (matching the expected output):

from collections import Counter

all_sorted = [['9', 's'], ['11', 'h'], ['2', 's'], ['13', 'c'], ['13', 's'], ['11', 's'], ['3', 'd']]
pairness = {**{str(i): 0 for i in range(14, 1, -1)}, **Counter(head for head, *_ in all_sorted)}

print(pairness)

Output

{'8': 0, '11': 2, '14': 0, '4': 0, '12': 0, '3': 1, '2': 1, '13': 2, '5': 0, '10': 0, '7': 0, '6': 0, '9': 1}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76