2

I have a list like this:

[(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]

That I need to convert to a tuple that looks like this:

[(0, [1, 2, 3]), (1, [4, 6, 7, 9])]

This is the code I have:

friends = open(file_name).read().splitlines()
network = []
friends = [tuple(int(y) for y in x.split(' ')) for x in friends]
return friends
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
K_P
  • 29
  • 2
  • Use [ast.literal_eval](https://docs.python.org/3/library/ast.html#ast.literal_eval) to parse the list from the file. – ekhumoro Nov 20 '17 at 03:23

3 Answers3

0

You can try this:

import itertools
s = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]
final_data = [(a, [i[-1] for i in list(b)]) for a, b in itertools.groupby(sorted(s, key=lambda x:x[0]), key=lambda x:x[0])]

Output:

[(0, [1, 2, 3]), (1, [4, 6, 7, 9])]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

This is not exactly what you ask for but from the kind of output you're looking for please let, me suggest you using defaultdict, it is super readable and efficient,

from collections import defaultdict

some_list = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]

d = defaultdict(list)

for k, v in some_list:
    d[k].append(v)

Output

defaultdict(<class 'list'>, {0: [1, 2, 3], 1: [4, 6, 7, 9]})
scharette
  • 9,437
  • 8
  • 33
  • 67
0

a 'one liner' nested list comprehension, with a line break

tpls = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]  

[(k, [tp[1] for tp in tpls if tp[0] == k])
 for k in set([*zip(*tpls)][0])]

Out[11]: [(0, [1, 2, 3]), (1, [4, 6, 7, 9])]

[*zip(*tpls)] is an idiom that 'transposes' the sub iterable

giving [(0, 0, 0, 1, 1, 1, 1), (1, 2, 3, 4, 6, 7, 9)]

so set([*zip(*tpls)][0]) is set((0, 0, 0, 1, 1, 1, 1))

which gives the unique items in the 1st position of the tuples in tpls: {0, 1}

which the outer for k in ... iterates over, providing k to the list comp inside the result tuple
[tp[1] for tp in tpls if tp[0] == k]

f5r5e5d
  • 3,656
  • 3
  • 14
  • 18