-1

我试图从我的书中提出一个问题,它问:

实现无需输入并反复要求用户输入学生名字的函数名称。当用户输入一个空白字符串时,该函数应该为每个姓名打印具有该姓名的学生人数。

示例用法:

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

4 回答 4

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
于 2013-03-11T08:13:54.903 回答
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循环 _
    • 让我们忽略..只是无效..在这里..

我们按如下方式解决这些问题(解决方案与上面解决的问题具有相同的编号)

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

尝试这个

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
于 2013-03-11T08:31:04.787 回答
0

函数中的命名存在很多问题,您正在使用诸如用于函数名称的“名称”之类的变量以及用于读取用户输入的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()

或者:

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
于 2013-03-11T07:59:54.667 回答
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()
于 2016-08-05T00:43:53.013 回答