【问题标题】:Finding the count of distinct values of an array and assigning them to another array查找数组的不同值的计数并将它们分配给另一个数组
【发布时间】:2017-03-03 14:49:17
【问题描述】:

我想找到数组 sorted_array 的不同值的计数。 在找到不同的值并将它们分配给 distinct_values 数组后,我想将值的计数分配给 distinct_values_count 数组上的相同位置,但我的代码似乎不起作用。 output.txt 文件看起来像这样:

1996
1983
1983
1982
1977
2011
1987
1988
1978
2012
2006
2013
> sorted_array = [] 
> distinct_values = []
> distinct_values_count = [0]
> file = open('output.txt', 'r')
> 
> for line in file:
>     sorted_array.append(line.split('\n'))
> 
> sorted_array.sort()
> 
> for i in range(0, len(sorted_array)):
>     year = sorted_array[i][0]
>     if year not in distinct_values:
>         distinct_values.append(year)
>     if year in distinct_values:
>         pos = distinct_values.index(year)
>         distinct_values_count[pos] = sorted_array.count(year)
> 
> file.close() 

我收到此错误:

IndexError: 列表赋值索引超出范围

【问题讨论】:

  • 使用 line.strip() 删除 '\n' 而不是 line.split('\n') 创建一个元素列表,然后将其附加到 sorted_array 多维。

标签: arrays python-3.x count


【解决方案1】:

您正在做的许多事情都可以在 Python 中更轻松地完成。与使用line.split('\n') 分割每一行创建的两级列表相比,处理平面列表肯定更容易。你这样做有什么原因吗?

创建文件内容的排序数组:

with open('/tmp/file') as f:
    sorted_array=sorted(line.strip() for line in f)

要获得不同的值,请使用集合:

distinct_values=set(sorted_array)   

获取不同值的计数:

distinct_value_count=[(e, sorted_array.count(e)) for e in distinct_values]

如果你想排序:

distinct_value_count=sorted((e, sorted_array.count(e)) for e in distinct_values)

然后:

>>> sorted_array
['1977', '1978', '1982', '1983', '1983', '1987', '1988', '1996', '2006', '2011', '2012', '2013']
>>> distinct_values
{'2011', '2006', '1996', '1978', '1977', '1987', '1983', '2012', '1982', '1988', '2013'}
>>> distinct_value_count
[('1977', 1), ('1978', 1), ('1982', 1), ('1983', 2), ('1987', 1), ('1988', 1), ('1996', 1), ('2006', 1), ('2011', 1), ('2012', 1), ('2013', 1)]

或者,使用字典来代替创建单独集合和计数的需要,因为字典的键也是唯一的(但无序):

>>> dv_dict={k:sorted_array.count(k) for k in set(sorted_array)}
>>> dv_dict
{'1996': 1, '2011': 1, '1978': 1, '1988': 1, '2013': 1, '1977': 1, '1987': 1, '2006': 1, '2012': 1, '1983': 2, '1982': 1}

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多