用python在列表中汇总数据

2024-10-02 08:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,我需要以如下方式汇总count_list中的数据(如直方图):

"""
number | occurence
  0 | *
  1 | **
  2 | ***
  3 | **
  4 | **
  5 | *
  6 | *
  7 | **
  8 | ***
  9 | *
  10 | **
"""

但是我得到了一个错误的输出:

^{pr2}$

这是我的代码:

import random
random_list = []
list_length = 20
while len(random_list) < list_length:
    random_list.append(random.randint(0,10))
count_list = [0] * 11
index = 0

while index < len(random_list):
   number = random_list[index]
    count_list[number] = count_list[number] + 1
    index = index + 1


def summerizer():
    index = 0
    print count_list
    print '"'*3
    print 'number  |  occurrence'
    while index < len(count_list):
      print '%s' %' '*(7),
      print index,#the problem is here
      print ' | ',#and here
      print '%s' %'*'*(count_list[index])
      index += 1
    print '%s'%'"'*3


summerizer()

Tags: 数据numberindexlenherecount方式random
3条回答

此方法使用^{}

from collections import Counter
import random

random_list = []
list_length = 20

while len(random_list) < list_length:
    random_list.append(random.randint(0,10))

c = Counter(random_list)

print('number  |  occurrence')
def summerizer(dic):
    for v,d in dic.items():
        print(v, '|', '%s'%'*'*c[v])

summerizer(dic)

试试这个

import random
random_list = []
list_length = 20
while len(random_list) < list_length:
    random_list.append(random.randint(0,10))
dic={}
for i in random_list:
    dic[i]=dic.get(i,0)+1
print 'number  |  occurrence'
for i in range(0,11):
    if(i not in dic):    
        print i,"|",'%s' %'*'*(0)
    else:
        print i,"|",'%s' %'*'*(dic[i])

输出

[9, 8, 4, 2, 5, 4, 8, 3, 5, 6, 9, 5, 3, 8, 6, 2, 10, 10, 8, 9]

^{pr2}$

是的,我发现了问题

它来自ide本身!!! 这是UDACITY android应用程序课程中的一个小测验,里面的嵌入式编译器给出了错误的答案。。在

我现在从Android上的pydroid应用程序中尝试过的相同代码也在没有任何改变的情况下给出了我需要的答案

谢谢你们的帮助

`import random
 random_list = []
 list_length = 20
 while len(random_list) < list_length:
  random_list.append(random.randint(0,10))
 count_list = [0] * 11
 index = 0

 while index < len(random_list):
  number = random_list[index]
  count_list[number] = count_list[number] + 1
  index = index + 1

def summerizer():
 index = 0
 print count_list
 print '"'*3
 print 'number  |  occurrence'
 while index < len(count_list):
  print '%s' %' '*(7),
  print index,
  print ' | ',
  print '%s' %'*'*(count_list[index])
  index += 1
 print '%s'%'"'*3

Summier()`

相关问题 更多 >

    热门问题