在Python3中数组列表的末尾添加数量

2024-04-18 23:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组表,每个数组都包含日志,每个数组的最后一个索引都有一个美元金额(0.01)。我需要对数组进行切片,然后对每个数组进行循环,将总数相加,输出一个总数。你知道吗

我一点也不知道怎么做。你知道吗

当我打印日志时,这就是它输出的内容,以供参考。你知道吗

@ 2014 2 14 00:03:01 Matt "login" 0.01
@ 2014 2 14 02:06:12 Mary "login" 0.01
@ 2014 2 14 07:12:05 Mary "cd ~/cs150/projects" 0.01
@ 2014 2 13 12:33:52 Boris "firefox&" 0.13
@ 2014 2 14 12:33:52 Boris "load http://yahoo.com" 0.01
@ 2014 2 15 03:42:27 Natasha "exit" 0.00

我计划在表中循环,切片数组以检索最后一个片段,将其添加到变量中,然后打印总数。你知道吗

谢谢你的帮助,我是新来的,在这件事上耽搁了一段时间。你知道吗


Tags: http内容cdloginload切片数组matt
3条回答

假设数据是列表列表,如下所示:

data = [['@', '2014', '2', '14', '00:03:01', 'Matt', '"login"', '0.01'],
['@', '2014', '2', '14', '02:06:12', 'Mary', '"login"', '0.01'],
['@', '2014', '2', '14', '07:12:05', 'Mary', '"cd ~/cs150/projects"', '0.01'],
['@', '2014', '2', '13', '12:33:52', 'Boris', '"firefox&"', '0.13'],
['@', '2014', '2', '14', '12:33:52', 'Boris', '"load http://yahoo.com"', '0.01'],
['@', '2014', '2', '15', '03:42:27', 'Natasha', '"exit"', '0.00']]

您可以将总数作为:

total = sum([Decimal(item[7]) for item in data])

如果数据在一个文件中,您可以在计算total之前读取该文件并如上所述构造data,具体操作如下:

import csv
data = []
with open('datafile', 'rb') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=' ')
    for row in csv_reader:
        data.append(row)

如果您认为美元金额始终表示为静态3位数浮动,则只需使用以下方法继续计划:

string.split()

要使用空格作为分隔符拆分字符串和/或:

dollars = float(string[-3:])

要获得美元的浮动金额:)

希望有帮助! 干杯, 亚历克斯

假设行位于文本文件中:

total=0.0
for line in open('filename'):
    total+=decimal(line.strip().split()[-1])

print total

相关问题 更多 >