Saturday 15 February 2014

python - Can I group / aggregate elements in a list (or dict) comprehension? -


I have a list of Tuplesses, as shown below:

  [ (1, "red, green") (1, "green, blue") (2, "green") (2, "yellow, blue")]   < P> I trying to roll data, so that I can get the following dick output:  
  {1: ["red", "green", "blue"] 2: Notes are: Colors of the colors are collected for the primary key (number), and then in a list different , And D-Duped (using  set  for example).  

I would also like to group with the inverse and the colors: < [1], "green": [1, 2] "yellow": [2] "blue": [1, 2]}

I can clearly do all the Tuples by looping it, but I will try and if possible, I would like to do this with the list / dict compilation.

You can use collections.defaultdict :

  & gt; & Gt; & Gt; Import from Collection will look the default & gt; & Gt; & Gt; Lis = [(1, "red"), (1, "red, green"), (1, "green, blue"), (2, "green"), (2, "yellow, blue")]] & Gt; & Gt; & Gt; Dic = defaultdict (set) #sets contains unique items only, in l: v [d] [k] .update (v.split (','))> gt; & Gt; & Gt; Set with (['blue', 'green', 'red']), 2: set (['blue', 'green', 'yellow']) (& lt; type 'set' Gt ;,})   

Now repeat on related :

  & gt; & Gt; & Gt; For Dic2 = defaultdict (list) k in v, dic.iteritems (): for val in: dic2 [val] .append (k) ... & gt; & Gt; & Gt; [2], 'red': [1]}) [2], '1'] [2], 'green': [1, 2], 'yellow': [2], 'red': [1] }    

No comments:

Post a Comment