我有一个采用以下格式的日志文件:
datetimestring \t username \t transactionName \r\n
我正在尝试对这个数据集进行一些统计分析。我有以下代码:
import time
import collections
file = open('Log.txt', 'r')
TransactionData = collections.namedtuple('TransactionData', ['transactionDate', 'user', 'transactionName'])
transactions = list()
for line in file:
fields = line.split('\t')
transactionDate = time.strptime(fields[0], '%Y-%m-%d %H:%M:%S')
user = fields[1]
transactionName = fields[2]
transdata = TransactionData(transactionDate, user, transactionName)
transactions.append(transdata)
file.close()
minDate = reduce(lambda x,y: min(x.transactionDate, y.transactionDate), transactions)
print minDate
我不想为这么简单的数据集定义一个类,所以我使用了命名元组。但是当我尝试运行时,出现了以下错误:
Traceback (most recent call last):
File "inquiriesStat.py", line 20, in <module>
minDate = reduce(lambda x,y: min(x.transactionDate, y.transactionDate), transactions)
File "inquiriesStat.py", line 20, in <lambda>
minDate = reduce(lambda x,y: min(x.transactionDate, y.transactionDate), transactions)
AttributeError: 'time.struct_time' object has no attribute 'transactionDate'
看起来Lambda函数直接操作'transactionDate'属性而不是传入整个元组。如果我将Lambda改为:
lambda x,y: min(x, y)
它按照我所期望的方式运作。有什么想法为什么会这样呢?