Friday, 15 April 2011

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



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

i using tuple store output of find -exec stat command , need condense in order run du on it. output tuple each item beingness (username,/path/to/file)

i want condense combine usernames end result (username,/path/to/file1,/path/to/file2,etc)

is there way this?

here current code returns tuple

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 = [] item in find_out: out_tuple.append(item.split(' '))

assuming have list of tuples or list of lists of form:

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

you can do:

from itertools import groupby out_tuple.sort() total_grouped = [] key, grouping in groupby(out_tuple, lambda x: x[0]): grouped_list = [key] + [x[1] x in group] total_grouped.append(tuple(grouped_list))

this give list of tuples:

print total_grouped # prints: # [('user_one', 'path_one', 'path_two', 'path_three'), # ('user_three', 'path_seven'), # ('user_two', 'path_five', 'path_four')]

if started list of lists, instead of:

total_grouped.append(tuple(grouped_list))

you can rid of tuple construction:

total_grouped.append(grouped_list)

i'll 1 thing though, might improve off using dict @bradbeattie suggests. if you're going perform operation later on treats first item in tuple (or list) in special way, dict better.

it not has notion of uniqueness in keys, it's less cumbersome because nesting has 2 distinct levels. first have dict, have inner item tuple (or list). much clearer having 2 similar collections nested 1 within other.

python python-2.7 tuples

No comments:

Post a Comment