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

Python 按计数对字符串输入进行分组,python,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: Th

我想问一个书中的问题,它问:

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

用法示例:

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]) 

我在这里真的迷路了,任何输入都会有帮助。另外,如果可能,请解释如何修复我的代码。函数中的命名有很多问题,您使用的变量包括用于函数名的“name”以及用于读取用户输入的python函数名的“input”——因此必须避免使用此变量。此外,您还将名称计数变量定义为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()
或:


我为你重写了你的函数:

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
执行
名称()
时:


让我们分析一下您的代码:

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]) 
似乎有一些问题,让我们列出它们

  • while
    循环的条件
    • 您要做的是检查用户的输入是否为
      '
      (无)
    • input
      是从用户获取输入的内置函数,因此它永远不会是
      (“”)
  • names=name
    语句
    • 您要做的是将
      名称
      添加到列表
      名称
    • 在这里,您正在将
      名称
      更改为字符串,这不是您想要的
  • if
    的条件
    • 与1相同
  • 用于循环的
    
    
    • 让我们忽略。。只是无效。。这里
  • 我们按如下方式解决这些问题(解决方案的编号与上面解决的问题相同)

  • 将条件更改为类似于
    name!=''的内容。
    此外,在循环开始之前,您需要获得一次输入,才能使其工作,在本例中,这有一个额外的好处,第一个输入可以有不同的提示
  • 使用
    名称。附加(名称)
    名称添加到
    名称中
  • 与1相同
  • 请看下面的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
    

    @NPE我想他是想解释我们的answers@Haidro是的,这就是我的意思,抱歉搞混了。我真的迷路了,我在这个问题上挣扎了一段时间。谢谢你的反馈!您的评论确实帮助我了解了代码是如何运行的works@JGrazza没问题:)。如果这个解决方案是有益的,欢迎接受:)你好。你把我对这个问题的答案从法语翻译成英语:()没什么大问题。但是你完全改变了内容,因此感觉。我没有提到SQL,你也提到了,加上了“处理各种基和文本可能会很复杂”,这意味着我使用正则表达式的答案不适用。那是你的意见,不是我的。我不欣赏。所以我删除了“我的”答案。@eyquem就是这么说的。。。所以,考虑一下谷歌的观点:很抱歉我刚刚添加了关于MySQL库的部分…谷歌的翻译是“做正确的事情。处理各种数据库和文本可能会很复杂”(顺便说一句,它应该做正确的事情,谷歌的翻译是不好的),但修改后的答案中的内容是“使用它需要的(一个合适的sql库)处理各种各样的基础和文本可能会很复杂。“你能假装它是一样的吗?”?我没有写一个合适的sql库,我没有使用它所需要的。此外,你复制的谷歌翻译来修改我的答案,以“…各种数据库和文本和“修改后的答案中有什么”…各种各样的基础和文本”结尾。每个短语中有两个“和”,但它们并没有放在同一个位置:很奇怪,假装你抄袭了第二个短语,而我读了第一个。闻起来好像你在欺骗我。哦,我刚刚看到你14岁。我会原谅你的。但是,14岁的家伙竟然敢修改别人的答案,真是太令人惊讶了!
    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]) 
    
    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
    
    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()