Exemple:
{"b":2, "e":1, "skip":1}
Résultats du dictionnaire:
list = ["a voted b", "c voted b", "d voted e", "e voted skip", "something else"]
6 Réponses :
Si les votes ont toujours la même structure x voted y
, vous pouvez faire:
# get a defaultdict for storing the result from collections import defaultdict result = defaultdict(int) # split out the voted from each string in the list pairs = [i.split(' voted ') for i in list] # for each pair, increase the value for that key in the defaultdict by 1 for _, vote in pairs: result[vote] += 1 # convert back to dict result = dict(result)
from collections import defaultdict mylist = ["a voted b", "c voted b", "d voted e", "e voted skip"] votes = defaultdict(int) for item in mylist: votes[item.split()[-1]] += 1
Qu'en est-il d'un one liner:
from collections import Counter result = dict(Counter([s.split(' voted ')[-1] for s in list]))
Je considère que la liste utilise le format suivant x voted y
qui change x et y. Aussi, j'ai décidé de ne pas utiliser de bibliothèque externe
Voici une fonction de mon code
def count(list): # Simplifying the list with the format 'x voted y' to a list with the format 'y' votes = [vote.split(' voted ')[1] for vote in list] result = {} for vote in votes: if vote in result.keys(): result[vote] = result[vote] + 1 else: result[vote] = 1
l = ["a voted b", "c voted b", "d voted e", "e voted skip"] v = {} for i in l: vs = i.split(' ') if vs[2] not in v: v[vs[2]] = 1 continue v[vs[2]] += 1
La manière la plus propre pourrait être d'utiliser des pandas
:
{'b': 2, 'skip': 1, 'e': 1}
résulte en:
lst = ["a voted b", "c voted b", "d voted e", "e voted skip"] pd.Series([i.split('voted')[1].strip() for i in lst]).value_counts().to_dict()