【问题标题】:Python script to sum values from ls -l outputPython 脚本对 ls -l 输出中的值求和
【发布时间】:2016-02-07 21:37:34
【问题描述】:

从其他帖子中,我可以读取 ls -l 的输出并仅过滤目录中的文件字节。但是,我还想将所有这些值放入一个列表(数组)中,然后得到元素的总和。

我尝试创建一个列表 b,然后只打印 sum(b)。但是,当我想创建一个列表时,我得到了 MemoryError。

现在的情况:

import subprocess
import csv
process = subprocess.Popen(['ls', '-l',], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()

reader = csv.DictReader(stdout.decode('ascii').splitlines(), delimiter = ' ', skipinitialspace=True, fieldnames= ['Owner','Date','Dir','Priv','Bytes','Field2', 'Field3', 'Field4', 'Field5'])

问题从这里开始

for row in reader:
    a = row['Bytes']
    b = [int(a)]
    for i in b:
        b.append(i)
    continue
    print(b)

输出:

Traceback (most recent call last):
  File "script2.py", line 13, in <module>
    b.append(i)
MemoryError

任何帮助如何将所有元素放入一个列表然后得到总和将不胜感激。谢谢!

【问题讨论】:

  • b.append(i) 尝试将i 添加到b,您正在尝试为数组中的每个i 添加i。而continue 跳到下一个循环,它永远不会打印b

标签: python unix dictionary ls


【解决方案1】:

要创建列表,您需要检查每一行的 row['Bytes'] 是否为空,如果不是,则转换为整数。一个很好的简洁方法是使用列表理解:

list_of_sizes = [int(row['Bytes']) for row in reader if row['Bytes']]

或者,同样的事情,使用更传统的 for 循环:

list_of_sizes = []
for row in reader:
    if row['Bytes']:
        list_of_sizes.append(int(row['Bytes']))

然后,你可以使用 sum 函数来计算总和:

total_size = sum(list_of_sizes)

【讨论】:

    【解决方案2】:

    您正在迭代 b 列表并将其元素添加到其中,它永远不会停止。

    for i in b:
        #b.append(i) #This is the problem
        #continue #Go to the next iteration
        print(i)
    

    编辑

    for row in reader:
        a = row['Bytes']
        print(a)
        b.append(int(a))
    

    【讨论】:

    • 谢谢,但这会打印从每一行读取的 1 个元素的列表。而且没有一个列表包含来自 b[a] 的所有元素
    • 谢谢,我改变了: a = row['Bytes'] b = [int(a)] for i in b: c.extend(b) continue 它给出了结果......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2014-02-10
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多