【问题标题】:Converting for to while loop将 for 转换为 while 循环
【发布时间】:2015-12-10 10:13:24
【问题描述】:

有人知道如何将其转换为 while 循环吗?

def function(number):
   dictionary_num = {}
   for i in number:
     if i in dictionary_num:
      dictionary_num[i] += 1
     else:
      dictionary_num[i] = 1

【问题讨论】:

  • 为什么不直接使用Counter() 呢? from collections import Counter; dictionary_num = Counter(number)。而已。无论如何,转换为while 循环将使循环更加冗长。为什么需要这样做?您需要一个单独的索引计数器,在循环中递增,然后使用while 循环直到计数器超过number 的长度...
  • 我从来没有使用过import,你能给我举个例子吗?
  • 给你:Standard Modules
  • @RobinDun:参见模块上的Python tutorial
  • 据说需要定义Counter?

标签: python loops converter


【解决方案1】:

技术答案:

def whloop(numbers):
    d = {}
    numbers = list(numbers)
    while numbers:
        i = numbers.pop()
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d

但是这样做真的没有意义......

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2017-04-26
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2020-06-20
    相关资源
    最近更新 更多