【问题标题】:Pythonic way to write for loops with nested if statements使用嵌套 if 语句编写 for 循环的 Pythonic 方法
【发布时间】:2018-06-06 10:21:06
【问题描述】:

假设我有一个包含费用类型的简单 python 列表,我想用 for 循环遍历这些费用。在每次迭代中,如果索引产生正确的费用类型,计数器将提前 1。我可以使用下面的代码轻松编写此代码,但它没有使用快速运行的 for 循环。

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
sum = 0
for i in range(len(array)):
    if array[i] == 'Groceries':
        sum += 1 

有没有更 Pythonic 的方式来编写这个加速执行的循环?我已经看到了类似于下面的代码 sn-p 的示例。注意:下面的代码sn-p不起作用,它只是我之前见过的加速格式的一个例子,但并不完全理解。

sum = [sum + 1 for i in array if array[i] == 'Groceries']

【问题讨论】:

    标签: python-3.x loops for-loop


    【解决方案1】:
    for i in range(len(array)):
    

    绝对是不是迭代数组的Python-ic方式。这是 VisualBasic 思维,你应该从中解放出来。

    如果你想遍历一个数组,只需按如下方式遍历它:

    array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
    for eachItem in array:
       ...
    

    你在循环中做什么取决于你。如果你想计算列表中有多少杂货,那么你可以这样做:

    array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
    groceriesTotal = 0
    for eachItem in array:
        if eachItem == 'Groceries':
             groceriesTotal = groceriesTotal + 1
    

    这是简单、清晰和 Python 的,足以被其他人阅读。

    【讨论】:

      【解决方案2】:

      您似乎认为您需要对此进行列表理解。但是列表推导会产生列表,并且您需要一个标量。试试array. count("Groceries")

      【讨论】:

        【解决方案3】:

        如果只是计数,请尝试collections.Counter

        from collections import Counter
        
        
        array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
        
        counts = Counter(array)
        
        print(counts)
        # Counter({'Groceries': 2, 'Bills': 1, 'Restaurant': 1, 'Misc': 1})
        
        print(counts['Groceries'])
        # 2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多