按计数对字符串输入进行分组

时间:2013-03-11 07:49:58

标签: python

我正试图从我的书中提出一个问题并且问:

  

实现不接受任何输入的函数名称并重复询问   用户输入学生的名字。当用户输入空白时   字符串,该函数应该打印每个名称,数量   有这个名字的学生。

使用示例:

Usage:
names()
Enter next name: Valerie
Enter next name: Bob
Enter next name: Valerie
Enter next name: John
Enter next name: Amelia
Enter next name: Bob
Enter next name: 
There is 1 student named Amelia
There are 2 students named Bob
There is 1 student named John
There are 2 students named Valerie

到目前为止,我有这段代码:

def names():
    names = []
    namecount = {a:name.count(a) for a in names}
    while input != (''):
        name = input('Enter next name: ')
        names = name
        if input == ('')
            for x in names.split():
                print ('There is', x ,'named', names[x]) 

我真的迷失在这里,任何投入都会有所帮助。如果可能的话,请解释如何修复我的代码

4 个答案:

答案 0 :(得分:0)

你的函数中有很多关于namings的问题,你正在使用诸如'names'这样的变量用于函数名称以及'input'这是一个用于读取用户输入的python函数名 - 所以你有避免使用这个。您还将namecount变量定义为dict并尝试在填充之前初始化它。因此,请尝试检查以下解决方案:

def myFunc():
    names = []
    name = ''
    while True: #bad stuff you can think on your own condition
        name = raw_input('press space(or Q) to exit or enter next name: ')
        if name.strip() in ('', 'q', 'Q'):
            for x in set(names):
                print '{0} is mentioned {1} times'.format(x, names.count(x))
            break
        else:
            names.append(name)

myFunc()

OR:

from collections import defaultdict

def myFunc():
    names = defaultdict(int)
    name = ''
    while True: #bad stuff you can think on your own condition
        name = raw_input('press space(or Q) to exit or enter next name: ')
        if name.strip() in ('', 'q', 'Q'):
            for x in set(names):
                print '{0} is mentioned {1} times'.format(x, names[x])
            break
        else:
            names[name] += 1

答案 1 :(得分:0)

我为你重写了你的功能:

def names():
    names = {} # Creates an empty dictionary called names
    name = 'cabbage' # Creates a variable, name, so when we do our while loop, 
                     # it won't immediately break
                     # It can be anything really. I just like to use cabbage
    while name != '': # While name is not an empty string
        name = input('Enter a name! ') # We get an input
        if name in names: # Checks to see if the name is already in the dictionary
            names[name] += 1 # Adds one to the value
        else: # Otherwise
            names[name] = 1 # We add a new key/value to the dictionary
    del names[''] # Deleted the key '' from the dictionary
    for i in names: # For every key in the dictionary
        if names[i] > 1: # Checks to see if the value is greater for 1. Just for the grammar :D
            print("There are", names[i], "students named", i) # Prints your expected output
        else: # This runs if the value is 1
            print("There is", names[i], "student named", i) # Prints your expected output

执行names()时:

Enter a name! bob
Enter a name! bill
Enter a name! ben
Enter a name! bob
Enter a name! bill
Enter a name! bob
Enter a name! 
There are 3 students named bob
There are 2 students named bill
There is 1 student named ben

答案 2 :(得分:0)

让我们分析您的代码:

def names():
    names = []
    namecount = {a:name.count(a) for a in names}
    while input != (''):
        name = input('Enter next name: ')
        names = name
        if input == ('')
            for x in names.split():
                print ('There is', x ,'named', names[x]) 

似乎有一些问题,让我们列出它们

  1. while循环的条件
    • 您要做的是检查来自用户的输入是''(无)......
    • input是一个内置函数,用于从用户那里获取输入,因此它永远不会是('')
  2. names = name声明
    • 您要做的是将name添加到列表names
    • 此处您正在将names更改为字符串,这不是您想要的。
  3. if的条件
    • 与1相同。
  4. for循环
    • 让我们忽略..只是无效......这里..
  5. 我们将这些问题解决如下(解决方案与上面解决的问题具有相同的编号)

    1. 将条件更改为name != ''之类的内容。 此外,在循环开始之前,您需要输入一次才能使其工作,在这种情况下有一个奖励,第一个输入可以有不同的提示。
    2. 使用names.append(name)name添加到names
    3. 与1相同。
    4. 请看下面的for循环......
    5. 试试这个

      def names():
          names = []
          name = input('Enter a name: ').strip() # get first name
          while name != '':
              names.append(name)
              name = raw_input('Enter next name: ').strip() # get next name
      
          for n in set(names): # in a set, no values are repeated
              print '%s is mentioned %s times' % (n, names.count(n)) # print output
      

答案 3 :(得分:0)

def names():
      counters = {}

      while True:
            name = input('Enter next name:')

            if name == ' ':
                  break

            if name in counters:
                  counters[name] += 1
            else:
                  counters[name] = 1
      for name in counters:
            if counters[name] == 1:
                  print('There is {} student named {}'.format(counters[name],name))
            else:
                  print('There are {} student named {}'.format(counters[name],name))


names()