How to map one list to another in python? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:56:01

问题:

This question already has an answer here:

['a','a','b','c','c','c'] 

to

[2, 2, 1, 3, 3, 3] 

and

{'a': 2, 'c': 3, 'b': 1} 

回答1:

>>> x=['a','a','b','c','c','c'] >>> map(x.count,x) [2, 2, 1, 3, 3, 3] >>> dict(zip(x,map(x.count,x))) {'a': 2, 'c': 3, 'b': 1} >>> 


回答2:

This coding should give the result:

from collections import defaultdict  myDict = defaultdict(int)  for x in mylist:   myDict[x] += 1 

Of course if you want the list inbetween result, just get the values from the dict (mydict.values()).



回答3:

Use a set to only count each item once, use the list method count to count them, store them in a dict with the item as key and the occurrence is value.

l=["a","a","b","c","c","c"] d={}  for i in set(l):     d[i] = l.count(i)  print d 

Output:

{'a': 2, 'c': 3, 'b': 1} 


回答4:

On Python ≥2.7 or ≥3.1, we have a built-in data structure collections.Counter to tally a list

>>> l = ['a','a','b','c','c','c'] >>> Counter(l) Counter({'c': 3, 'a': 2, 'b': 1}) 

It is easy to build [2, 2, 1, 3, 3, 3] afterwards.

>>> c = _ >>> [c[i] for i in l]   # or map(c.__getitem__, l) [2, 2, 1, 3, 3, 3] 


回答5:

a = ['a','a','b','c','c','c'] b = [a.count(x) for x in a] c = dict(zip(a, b)) 

I've included Wim answer. Great idea



回答6:

Second one could be just

dict(zip(['a','a','b','c','c','c'], [2, 2, 1, 3, 3, 3])) 


回答7:

For the first one:

l = ['a','a','b','c','c','c']

map(l.count,l)



回答8:

d=defaultdict(int) for i in list_to_be_counted: d[i]+=1 l = [d[i] for i in list_to_be_counted] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!