我有一个如下列表:
import subprocess
last_logins = [i.split(' ', 1)[0] for i in subprocess.check_output('last').split('\n') if 'reboot' not in i]
print("The last five logins were: {0}".format(', '.join(last_logins[0:5])))
它返回:
The last five logins were: vagrant, vagrant, vagrant, vagrant, vagrant
如何嵌套保持用户记录的子循环,在这种情况下,返回:
The last five logins were: vagrant: 2x, some_other_user: 3x
是的,它很难看,理解线太长了。 (我对编写更清晰的代码的批评/建议持开放态度)。但我也想找到在(列表)理解中嵌套循环的正确方法。
答案 0 :(得分:2)
我认为您正在寻找collections.Counter()
:
from collections import Counter
last_logins = ['Vagrant', 'Vagrant', 'Some Other User', 'Vagrant', 'Some Other User']
last_five_stats = Counter(last_logins[:5])
print("The last five logins were: {0}".format(', '.join("{0}: {1}x".format(user, count) for user, count in last_five_stats.items())))
打印:
The last five logins were: Vagrant: 3x, Some Other User: 2x
这对f-strings
(Python 3.6 +)来说会更好一些:
last_five_stats = (f"{user}: {count}x" for user, count in Counter(last_logins[:5]).items())
print(f"The last five logins were: {', '.join(last_five_stats)}")