python 如何在python中将一个列表映射到另一个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2401885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:34:21  来源:igfitidea点击:

How to map one list to another in python?

python

提问by user288832

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

to

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

and

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

回答by YOU

>>> 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}
>>>

回答by Juergen

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()).

当然,如果您想要结果之间的列表,只需从字典(mydict.values())中获取值。

回答by Mizipzor

Use a setto only count each item once, use the list method countto count them, store them in a dictwith the item as key and the occurrence is value.

使用aset只对每个item计数一次,使用list方法count计数,dict以item为key存储在a中,出现次数为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}

回答by kennytm

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

在 Python ≥2.7 或 ≥3.1 上,我们有一个内置的数据结构collections.Counter来统计一个列表

>>> 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.

[2, 2, 1, 3, 3, 3]之后很容易建立。

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

回答by luc

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

我已经包含了 Wim 的答案。好点子

回答by Wim

Second one could be just

第二个可能只是

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

回答by JonT

For the first one:

对于第一个:

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

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

map(l.count,l)

地图(l.count,l)

回答by starhusker

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