我正在使用一个元组来存储 find -exec stat
命令的输出,并且需要压缩它以便在其上运行 du。输出是一个元组,每个项目都是 (username,/path/to/file)
我想将它压缩成像用户名一样组合,所以最终结果是 (username,/path/to/file1,/path/to/file2,etc)
有什么办法吗?
这是返回我的元组的当前代码
cmd = ['find',dir_loc,'-type','f','-exec','stat','-c','%U %n','{}','+']
process = Popen(cmd,stdout=PIPE)
find_out = process.communicate()
exit_code = process.wait()
find_out = find_out[0].split('\n')
out_tuple = []
for item in find_out:
out_tuple.append(item.split(' '))
最佳答案
假设您有一个 list
的 tuples
或 list
的 lists
形式:
out_tuple = [('user_one', 'path_one'),
('user_three', 'path_seven'),
('user_two', 'path_five'),
('user_one', 'path_two'),
('user_one', 'path_three'),
('user_two', 'path_four')]
你可以这样做:
from itertools import groupby
out_tuple.sort()
total_grouped = []
for key, group in groupby(out_tuple, lambda x: x[0]):
grouped_list = [key] + [x[1] for x in group]
total_grouped.append(tuple(grouped_list))
这将为您提供元组
的列表
:
print total_grouped
# Prints:
# [('user_one', 'path_one', 'path_two', 'path_three'),
# ('user_three', 'path_seven'),
# ('user_two', 'path_five', 'path_four')]
如果您从 lists
的 list
开始,那么代替:
total_grouped.append(tuple(grouped_list))
你可以去掉 tuple
结构:
total_grouped.append(grouped_list)
不过我要说一件事,你最好使用像@BradBeattie 建议的 dict
这样的东西。如果您稍后要执行一些操作,以特殊方式处理 tuple
(或 list
)中的第一项,那么 dict
更好。
它不仅在键中具有唯一性的概念,而且由于嵌套有两个不同的级别,因此也不那么麻烦。首先你有 dict
,然后你有内部项,它是一个 tuple
(或 list
)。这比将两个相似的集合一个嵌套在另一个集合中要清晰得多。
关于 python 2 : How do I condense like terms in a tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440206/