[英]Sorting and Grouping Nested Lists Consists of Class Objects
我有數百個文本文件,需要根據用戶名和日期進行解析。 我試圖將有用的數據放在像這樣的列表中的文本文件中:
[
['1234245@gmail.com', '34209809' '1434546354', '2016-07-18 00:20:58'],
['abcd@gmail.com', '234534345', '09402380',, '2016-07-18 00:20:03'],
['username@gmail.com', '345315531','1098098098', '2016-07-18 02:40:00'],
['abcd@gmail.com', '345431353', '231200023', '2016-07-18 15:45:49'],
['1234245@gmail.com', '23232424', '234809809', '2016-07-18 20:45:40']
]
但是,我想根據日期時間和用戶名對它們進行排序,因此輸出如下:
[
['1234245@gmail.com', '23232424', '234809809', '2016-07-18 20:45:40'],
['1234245@gmail.com', '34209809' '1434546354', '2016-07-18 00:20:58'],
['abcd@gmail.com', '345431353', '231200023', '2016-07-18 15:45:49'],
['abcd@gmail.com', '234534345', '09402380',, '2016-07-18 00:20:03'],
['username@gmail.com', '345315531','1098098098', '2016-07-18 02:40:00']
]
這是我的代碼:
import glob
from operator import itemgetter
from itertools import groupby
def read_large_file(filename):
matrix=[]
global username
username=[]
for myfile in glob.glob(filename):
infile = open(myfile, "r")
for row in infile:
row=row.strip()
array=row.split(';')
username.append(array[9])
matrix.append(cdr(array[9],array[17],array[18],array[8]))
return matrix
class cdr(object):
def__init__(self,username,total_seconds_since_start,download_bytes,date_time):
self.username=username
self.total_seconds_since_start=total_seconds_since_start
self.download_bytes=download_bytes
self.date_time=date_time
def GroupByUsername(matrix):
new_matrix=[]
new_matrix=groupby(matrix, itemgetter(0))
return new_matrix
matrix=read_large_file('C:\Users\ceren\.spyder2/test/*')
matrix_new=GroupByUsername(matrix)
我試圖在此鏈接中使用該解決方案: 在Python中對嵌套列表進行排序和分組,但是我遇到了以下錯誤:
'cdr' object does not support indexing
'cdr' object is not iterable
您可能只可以使用簡單的Python內置排序。
sorted_list = sorted(data, key=lambda user_info: (user_info[0], user_info[3]))
lambda鍵告訴Python如何對列表進行排序(升序)。 對於data
每個條目, user_info
將是4個屬性的列表。 因此, user_info[0]
將是電子郵件,而user_info[3]
將是日期時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.