Skip to main content
 首页 » 编程设计

python之如何修复我的代码以累积具有相同日期和用户名以及返回时间 python 的项目

2024年12月31日9qlqwjy

如何重写这段代码,使其不显示总时间的累计值,而是显示重复登录的那些天每个用户的累计时间值。

for item in x: 
    #x = usage_report.get_login_rec() 
    b = item[14].strip('()') 
    a = time.strptime(b, "%M:%S") 
    c = int(a.tm_sec) 
    b.strip(':') 
    if item[2:5]: 
        test += c 
        d.append(test) 
        f.append(test) 
        t.append([item[0], item[3] , item[4], item[5], str(b) ,test]) 
print(*t, sep='\n') 

这是我得到的返回:

['root', 'Thu', 'May', '10', '00:10', 2285] 
['tom', 'Tue', 'May', '8', '01:00', 2300] 
['root', 'Tue', 'May', '8', '00:20', 2400] 
['root', 'Tue', 'May', '8', '00:20', 2429] 
['root', 'Tue', 'May', '8', '00:20', 2514] 
['root', 'Tue', 'May', '8', '00:20', 2552] 
['(unknown)', 'Tue', 'May', '8', '00:00', 2552] 
['(unknown)', 'Mon', 'May', '7', '00:12', 2564] 

预期输出:

['root', 'Thu', 'May', '10','00:10' , 10] 
['root', 'Tue', 'May', '8', '1:20', 120] 
['tom', 'Tue', 'May', '8', '00:60', 60] 
['(unknown)', 'Tue', 'May', '8', '00:00', 0] 
['(unknown)', 'Mon', 'May', '7', '00:12', 12] 

x =

def get_login_rec(): 
    raw_login_rec = [ x.split() for x in os.popen('last -F -i -w').read().split('\n')] 
    login_rec = [] 
    bad_rec = [] 
    for rec in raw_login_rec: 
        if len(rec) == 15: 
            login_rec.append(rec) 
        else: 
            bad_rec.append(rec) 
    return login_rec 

请您参考如下方法:

要实现您想要的效果,您可以创建一个 dict 对象,该对象的键是元组 (, ),值是累加和。在伪代码中它可能看起来像这样:

userActivityMap = {} 
for item in x: 
    # I assume item[3], item[4] and item[5] are strings here so use '+' 
    key = (item[0], item[3] + '_' + item[4] + '_' + item[5]) 
    if key not in userActivityMap: 
        userActivityMap[key] = 0     
    userActivityMap[key] += <time value> 
 
for item in userActivityMap: 
    print(item[0], ' '.join(item[1].split('_')), userActivityMap[item])