【问题标题】:Getting different results when incrementing a variable using a list comprehension vs a for loop使用列表推导与 for 循环递增变量时获得不同的结果
【发布时间】:2020-07-03 23:32:52
【问题描述】:

使用列表推导和 for 循环递增变量时得到不同的结果

counter = 0
counter2 = 0
counter3 = 0

Items_lst = os.listdir()

lst = [i for i in Items_lst if os.path.isfile(i) and i != os.path.basename(__file__)]

for i in lst:
    counter += os.path.getsize(i)

counter2 = sum([os.path.getsize(i) for i in lst])

[counter3 := os.path.getsize(i) for i in lst]

print(counter)
print(counter2)
print(counter3)

输出:

5678203604   # counter
5678203604   # counter2
5421459456   # counter3

这是怎么回事?!! :=到底是做什么的??

【问题讨论】:

  • .... 它分配给一个变量,这正是它正在做的事情。你什么都不做add,你为什么认为counter3会神奇地知道你想要求和?在任何情况下,你真的不应该使用这样的列表理解开始

标签: python-3.x for-loop list-comprehension


【解决方案1】:

问题是 counter3 并没有真正计数。 := (“海象运算符”)仅分配;它不求和。见这里:https://docs.python.org/3/whatsnew/3.8.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2020-06-11
    • 2011-10-15
    • 2011-10-06
    相关资源
    最近更新 更多