【问题标题】:Counting the input in a while loop?在while循环中计算输入?
【发布时间】:2013-02-27 07:18:35
【问题描述】:

我需要帮助我编写一个函数,其中包括一个 while 循环,该循环将继续运行,直到用户输入一个空输入,一旦发生这种情况,该函数将返回输入名称的次数

到目前为止,我的代码是:

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

    lst = name.split()
    count={}
    for n in lst:
        if n in count:
            count[n]+=1

    for n in count:
        if count[n] == 1:
            print('There is {} student named {}'.format(count[n],\
                                                    n))
        else:

            print('There are {} students named {}'.format(count[n],\
                                                        n))

这里不再重复,只询问用户一次并返回 1

输出应如下所示:

Enter next name:Bob
Enter next name:Mike
Enter next name:Bob
Enter next name:Sam
Enter next name:Mike
Enter next name:Bob
Enter next name:

There is 1 student named Sam
There are 2 students named Mike
There are 3 students named Bob

【问题讨论】:

    标签: python string python-3.x while-loop counter


    【解决方案1】:

    以下内容有点矫枉过正。这只是为了知道有标准模块collections,它包含Counter 类。无论如何,我更喜欢问题中使用的简单解决方案(在删除错误之后)。第一个函数读取输入并在输入空名称时中断。第二个函数显示结果:

    #!python3
    
    import collections
    
    
    def enterStudents(names=None):
    
        # Initialize the collection of counted names if it was not passed
        # as the argument.
        if names is None:
            names = collections.Counter()
    
        # Ask for names until the empty input.
        while True:
            name = input('Enter a name: ')
    
            # Users are beasts. They may enter whitespaces.
            # Strip it first and if the result is empty string, break the loop.
            name = name.strip()
            if len(name) == 0:
                break
    
            # The alternative is to split the given string to the first
            # name and the other names. In the case, the strip is done
            # automatically. The end-of-the-loop test can be based 
            # on testing the list.
            #
            # lst = name.split()
            # if not lst:
            #     break
            #
            # name = lst[0]
            #                   (my thanks to johnthexiii ;)
    
    
            # New name entered -- update the collection. The update
            # uses the argument as iterable and adds the elements. Because
            # of this the name must be wrapped in a list (or some other 
            # iterable container). Otherwise, the letters of the name would
            # be added to the collection.
            #
            # The collections.Counter() can be considered a bit overkill.
            # Anyway, it may be handy in more complex cases.    
            names.update([name])    
    
        # Return the collection of counted names.    
        return names
    
    
    def printStudents(names):
        print(names)   # just for debugging
    
        # Use .most_common() without the integer argument to iterate over
        # all elements of the collection.
        for name, cnt in names.most_common():
            if cnt == 1:
                print('There is one student named', name)
            else:
                print('There are {} students named {}'.format(cnt, name))
    
    
    # The body of a program.
    if __name__ == '__main__':
        names = enterStudents()
        printStudents(names)
    

    部分代码可以删除。 enterStudents() 中的 name 参数允许调用函数以将名称添加到现有集合。对None的初始化用于将空的初始集合设为默认集合。

    name.strip() 如果您想收集所有内容(包括空格),则不需要。

    它打印在我的控制台上

    c:\tmp\___python\user\so15350021>py a.py
    Enter a name: a
    Enter a name: b
    Enter a name: c
    Enter a name: a
    Enter a name: a
    Enter a name: a
    Enter a name:
    Counter({'a': 4, 'b': 1, 'c': 1})
    There are 4 students named a
    There is one student named b
    There is one student named c    
    

    【讨论】:

    • 如果你打算去那些长度应该考虑规范化输入(即用户 .lower())。应该可能使用 raw_input 而不是 input。您没有从放入 Counter 中的内容中删除空白,不确定 Counter 是否自行处理。
    • @johnthexiii:我的 +1。他或她使用 Python 3——那么input() 就可以了。添加了剥离。在 cmets 中使用 .split() 的替代方案。感谢 cmets ;)
    【解决方案2】:

    除了您从未将n 添加到您的count 字典这一事实之外,您会在while 循环的每次迭代中一次又一次地初始化该字典。你必须把它放在循环之外。

    count= {}
    
    while True:
        name = input('Enter a name:')
    
        lst = name.split()
        for n in lst:
            if n in count:
                count[n] += 1
            else:
                count[n] = 1
    
        for n in count:
            if count[n] == 1:
                print('There is {} student named {}'.format(count[n],\
                                                        n))
            else:
    
                print('There are {} students named {}'.format(count[n],\
                                                            n))
    

    【讨论】:

      【解决方案3】:

      @zzk 的意思是

      for n in lst:
          if n in count:
              count[n]+=1
          else:
              count[n]=1
      

      使用每个人的建议来获得最有效的答案

      count= {}
      
      while True:
      
          name = raw_input('Enter a name:')
          lst = name.split()
      
          for n in lst:
              count[n] = count.get(n, 0) + 1
      
          if not lst:
              for n in count:
                  if count[n] == 1:
                      print('There is {} student named {}'.format(count[n],n))
                  else:
                      print('There are {} students named {}'.format(count[n],n))
              break
      

      【讨论】:

      • if以下的四行可以替换为count[n] = count.get(n, 0) + 1.get()[] 类似,但它可以采用默认值。
      【解决方案4】:
          for n in lst:
              if n in count:
                  count[n]+=1
      

      在您的上述代码中,n 永远不会添加到您的 count 字典中。即count 在循环之后仍然是空的..

      【讨论】:

      • 其实一开始+= 1KeyError 会失败。这是因为n 没有任何价值。
      • @pepr 没有。 count[n]+=1 不会被执行,因为 n in countFalse
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2021-09-14
      • 2020-06-08
      • 2016-06-25
      • 2016-04-26
      • 1970-01-01
      相关资源
      最近更新 更多