我正在尝试编写一个函数,该函数接受一个数组,并返回一个dictonary,其中的键表示列表中的唯一值,而一个值是列表中每个项的计数。
Path path = new Path (filename);
FileSystem fs = FileSystem.getLocal(context.getConfiguration());
BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
我希望
def freq(arr):
sum = 0
dict = {}
for i in arr:
if i not in dict:
dict[i] = 1
else:
dict[i] =+ 1
return dict
print(count([1,2,3,4,5,100,100,1000]))
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1, 100: 1}
答案 0 :(得分:3)
collections.Counter
已经做了你想做的事。
from collections import Counter
c = Counter([1,2,3,4,5,100,100,1000])
print(c)
# Counter({100: 2, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
答案 1 :(得分:0)
因此,为了减少代码并使其更具可读性,您可以使用默认的 dict 来代替。要使用默认 dict,首先必须从 collections 模块导入它,然后创建默认 dict 对象。默认字典要求我给它一个叫做工厂函数的东西。在这种情况下,我将给它整数类,它本质上将充当默认值的创建者,以便如果我尝试访问一个不存在的键,它将为我创建一个默认值使用这个对象作为构造函数,并且由于创建一个新的 int 对象将值初始化为零,我现在可以访问任何键,并增加它而无需检查它是否已经存在。
所以你必须先导入 defaultdict。
from collections import defaultdict
# your list of numbers
nums = [1,2,3,4,5,100,100,1000]
# use a default dictionary to count each element
numCounter = defaultdict(int)
# Count the elements in the list
for num in nums:
numCounter[num] += 1
# print the result
for (k, v) in numCounter.items():
print(str(k) + ": " + str(v))
输出将是
1:1,
2:1,
3:1,
4:1,
5:1,
100:2,
1000:1