English 中文(简体)
Converting a Tuples List into a nested List using Python
原标题:

I want to convert a tuples list into a nested list using Python. How do I do that?

I have a sorted list of tuples (sorted by the second value):

[(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), 
 (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]

Now I want it to have like this (second value ignored and nested in lists):

[ [1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2] ]

I ve seen other threads in here with map used for such things, but I don t completely understand it. Can anyone provide insight as to the correct python way of doing this?

最佳回答
from operator import itemgetter
from itertools import groupby

lst = [(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1),
       (12, 1), (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]

result = [[x for x, y in group]
          for key, group in groupby(lst, key=itemgetter(1))]

groupby(lst, key=itemgetter(1)) generates groups of consecutive elements of lst within which all elements have the same 1st (counting from zero) item. The [x for x, y in group] keeps the 0th item of each element within each group.

问题回答

It is a bit convoluted, but you can do it with the itertools.groupby function:

>>> lst = [(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1), (12, 1), 
 (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]
>>> from operator import itemgetter 
>>> import itertools
>>> [map(itemgetter(0), group) for (key,group) in itertools.groupby(lst, itemgetter(1))]
[[1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2]]
>>> 

Explanation: groupby returns an iterator for each group, where a group is defined as a sequence of entries that have the same value returned by function passed as a separate parameter. itemgetter(1) generates a function that returns x[1] when called with argument x. Since the groupby iterator returns two values - the key that was used and sequences of the original values which are tuples, we then need to strip out the second value in each tuple, which is what map(itemgetter(0), group) does.

Maybe not the most pythonesque answer, but this works:

d = {}

a = [(1,5), (5,4), (13,3), (4,3), (3,2), (14,1), (12,1)]

for value in a:
     if value[0] not in d:
         d[ value[0] ] = []
     d[ value[0] ].append( a[1] )

print d.values()

The simple solution:

n_list = []
c_snd = None
for (fst, snd) in o_list:
  if snd == c_snd: n_list[-1].append(fst)
  else:
    c_snd = snd
    n_list.append([fst])

Explanation: use c_snd to store the current second part of the tuple. If that changes, start a new list in n_list for this new second value, starting with fst, otherwise add fst to the last list in n_list.

Don t know how fast this will be for bigger sets, but you could do something like that:

input = [
    (1,  5), (5,  4), (13, 3), (4, 3), (3, 2), (14, 1),
    (12, 1), (10, 1), (9,  1), (8, 1), (7, 1), (6,  1),
    (2,  1)
]

output = [[] for _ in xrange(input[0][1])]
for value, key in input:
    output[-key].append(value)

print output # => [[1], [5], [13, 4], [3], [14, 12, 10, 9, 8, 7, 6, 2]]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签