计算python中另一个列表中每个列表项的频率
问题描述:
我试图获得列表中最后一位数字出现在列表中的频率,并且有相当多的麻烦。计算python中另一个列表中每个列表项的频率
基本上这是我试图创建函数:
>>> ones_digit_histogram([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765])
[0.09523809523809523, 0.19047619047619047, 0.047619047619047616, 0.14285714285714285, 0.14285714285714285, 0.14285714285714285, 0, 0.14285714285714285, 0.047619047619047616, 0.047619047619047616]
,这是我迄今为止
def last_digit(number):
last_digit = str(number)[-1]
last_digit = int(last_digit)
return last_digit
def ones_digit_of_each_list_item(num_list):
returned_list = []
for list_value in num_list:
returned_list = (returned_list + [last_digit(list_value)])
return returned_list
print ones_digit_of_each_list_item([123, 32, 234, 34, 22])
我遇到的麻烦包括获得的
结果ones_digit_of_each_list_item([123, 32, 234, 34, 22])
被包含在找到发生频率(以百分比形式)中清单[123, 32, 234, 34, 22]
答
数字的最后一位数字是数字除以十的余数,因此您可以使用%
运算符更高效地计算它。
在构建结果列表时,不是连接列表,而是将新值添加到新列表中,最好是.append()
。或者更好地使用列表理解。
def last_digit(number):
return number % 10
def one_digit_of_each_list_number(number_list):
return [last_digit(number) for number in number_list]
然后,你只需要算(现在只有十位数可能,所以最好使用比字典列表)每个数字出现的次数,然后通过总数除以项目。
def ones_digit_histogram(number_list):
histogram = [0] * 10
for digit in one_digit_of_each_list_number(number_list):
histogram[digit] += 1
return [float(x)/len(number_list) for x in histogram]
然后,您为例,你会得到:
>>> print ones_digit_histogram([123, 32, 234, 34, 22])
[0.0, 0.0, 0.4, 0.2, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0]
数字'1'在您的最后一个例子发生一次,所以它的结果不能'0.0'。 – pemistahl 2013-02-15 09:33:11
根据OP的要求,它绝不会出现在最后的位置。 – 2013-02-15 09:35:43
糟糕,真的。我的错。 – pemistahl 2013-02-15 09:36:11