python 2 : How do I condense like terms in a tuple?

标签 python python-2.7 tuples

我正在使用一个元组来存储 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(' '))

最佳答案

假设您有一个 listtupleslistlists 形式:

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')]

如果您从 listslist 开始,那么代替:

    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/

相关文章:

python - 递归函数内的全局计数

python - 在python中导入/读取csv文件,然后绘图,给出x=y图?

python - 使用范围使用自定义排序功能对元组进行排序?

Python-将元组列表拆分为子列表

python - 元组到字典 :one key and multiple values

Python:从文件中读取和替换字符串(带有特殊字符)时出错

python - 在 Django 中使用 '_id'

python - App Engine 中的处理程序测试失败 : webtest import errors

python - 使用哪个更安全? uuid,binascii.hexlify(os.urandom()) 或 random.SystemRandom()?

python - 在 python 字典中使用变量作为键名