【问题标题】:need advice on strings/numbers Python.3x需要关于字符串/数字的建议 Python.3x
【发布时间】:2014-08-16 18:08:29
【问题描述】:

所以到目前为止我的代码是计算每个字符的数量并且它可以工作,但调整是我需要以某种方式将数字替换为“星号”('*')。让我举个例子,这样更容易理解。

entert text please.
HEY hei

现在是:

histogram:
e: 2
h: 2
i: 1
y: 1

想要:

histogram:
e: **
h: **
i: *
y: *

有些人想知道,是的,这是学校作业的一部分,我不想使用 Collection / counter

def count_dict(mystring):
    d = {}
    # count occurances of character
    for w in mystring:
        d[w] = mystring.count(w)
    # print the result
    print("histogram:")
    for k in sorted(d):
        (str(d[k])).replace(isdigit(), '*')
        print (k +': ' + str(d[k]))

mystring = input("entert text please.\n").lower().replace(' ', '')

count_dict(mystring)

已解决

编辑:

这个小技巧成功了:

m = int(str(d[k]))
        print (k +': ' + m*'*')

【问题讨论】:

  • 你知道print('!' * 3) 打印'!!!'
  • TypeError: 不能将序列乘以“str”类型的非整数
  • 不得不将其强制转换为 int --> m = int(str(d[k])) 然后 print(m*'*')
  • d[k] 已经是一个 int。所以m=d[k] 或简单地使用d[k] 而不是m 更简单。

标签: python string python-3.x counter


【解决方案1】:

这里有一个提示:

>>> '*'*2
'**'

>>>> '*'*3
'***'

【讨论】:

    【解决方案2】:

    你可以制作一个字母计数字典

    s = 'Hello world this is my sentence'
    unique_letters = filter(lambda i : i.isalpha(), set(s.lower()))
    

    这是一组 unique_letters

    ['c', 'e', 'd', 'i', 'h', 'm', 'l', 'o', 'n', 's', 'r', 't', 'w', 'y']
    

    我们可以利用* 操作来制作星号字符串。这可以在 dict comp 中完成。

    star_dict = {i : '*' * s.count(i) for i in unique_letters}
    

    star_dict 现在是

    {'c': '*', 'e': '****', 'd': '*', 'i': '**', 'h': '*', 'm': '*', 'l': '***', 'o': '**', 'n': '**', 's': '***', 'r': '*', 't': '**', 'w': '*', 'y': '*'}
    

    然后打印出来:

    for key in star_dict:
        print key, ':', star_dict[key]
    
    c : *
    e : ****
    d : *
    i : **
    h : *
    m : *
    l : ***
    o : **
    n : **
    s : ***
    r : *
    t : **
    w : *
    y : *
    

    【讨论】:

      【解决方案3】:

      您可以使用计数器:

      s='HEY hei'
      
      from collections import Counter
      
      hist=Counter(c for c in s.lower() if c.strip())
      for l, c in hist.most_common():
          print('{}:{}'.format(l, '*'*c))
      

      打印:

      e:**
      h:**
      i:*
      y:*
      

      如果您不能使用 Counter,您可以使用“老式方式”:

      count={}
      for e in (c for c in s.lower() if c.strip()):
          count[e]=count.setdefault(e, 0)+1
      
      for k, v in sorted(count.items(), key=lambda t:-t[1]):
          print('{}:{}'.format(k, '*'*v))      
      

      【讨论】:

      • 您好,感谢您的回复,但是:有些人想知道,是的,这是学校作业的一部分,我不想使用 Collection / counter
      • defaultdict? (不像 setdefault 那样神秘......)
      • 好吧,如果他不能从collections 使用Counter,我想他可能不能从同一个模块使用defaultdictsetdefaultdict 的本机方法,自预版本 2 起。
      猜你喜欢
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 2013-05-31
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      相关资源
      最近更新 更多