Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中将此列表更改为另一个列表的函数方式_Python_Python 3.x_Algorithm_Functional Programming - Fatal编程技术网

python中将此列表更改为另一个列表的函数方式

python中将此列表更改为另一个列表的函数方式,python,python-3.x,algorithm,functional-programming,Python,Python 3.x,Algorithm,Functional Programming,我有一个列表[2,3,0,3] 并希望生成一个列表 [1,0,1,2] 原因是输入列表中出现1个零,没有人出现,1个2和2个3 在python中是否有一种非for-loopy过程方法来实现这一点?您可能可以使用以下代码: lst = [2,3,0,1,3] #Get list unique values using set set_lst = sorted(set(lst)) #For each unique element, use the count method counts = [ls

我有一个列表[2,3,0,3] 并希望生成一个列表

[1,0,1,2]
原因是输入列表中出现1个零,没有人出现,1个2和2个3


在python中是否有一种非for-loopy过程方法来实现这一点?

您可能可以使用以下代码:

lst = [2,3,0,1,3]
#Get list unique values using set
set_lst = sorted(set(lst))
#For each unique element, use the count method
counts = [lst.count(i) for i in set_lst]
首先,我们使用一个只存储唯一元素的set对象找出列表中所有唯一的元素。然后我们遍历列表,并使用count方法获得每个元素的计数,这些计数按顺序排序。

您可以使用which查找元素计数:

from collections import Counter

lst = [2,3,0,3]

c = Counter(lst)
print([c[x] for x in range(max(lst)+1)])
# [1, 0, 1, 2]
避免循环的另一种方法:

from collections import Counter

lst = [2,3,0,3]

c = dict.fromkeys(range(max(lst)+1), 0)
c.update(Counter(lst))

print(c.values())
# # [1, 0, 1, 2]
另一个具有count的解决方案:

如果您想以任何价格避免使用for关键字,则可以使用map,方法如下:

a = [2,3,0,3]
out = list(map(lambda x:a.count(x), list(range(max(a)+1))))
print(out) #[1, 0, 1, 2]

此解决方案假设a仅包含非负整数,并且不是空列表。

使用a,它类似于数据库中的分组操作。感谢Nishant,guy ubnutu显示计数器,非常接近,但我更新了我的问题,使其缺少1。您的输出列表应为最小-最大值或0-最大值。假设列表为[5,9,7]输出应该是什么?这类似于[my_counter[i]for i in rangemaxmy_counter],我认为这是一种更内置的方法。很明显,使用计数器或itertools可能更快,但更重要的是看看Austins的答案,更优雅,看到其他想法总是很有趣,但由于需要断言,我仍然喜欢相反的方式,有一个向上的投票
a = [2,3,0,3]
out = list(map(lambda x:a.count(x), list(range(max(a)+1))))
print(out) #[1, 0, 1, 2]