hutpiche
hutpiche

Reputation: 23

How to separate a list into two different lists ?(Python2.7)

My current data is in the format of :

[  1982,      1, 108108,   5568],
[  1982,      2,  64488,   2433],
..., 
[  2007,    498,   4341,    395],
[  2007,    499,   4328,    274],
[  2007,    500,   4323,   -118]]

I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list.

How would I do this?

Upvotes: 0

Views: 67

Answers (4)

RoadRunner
RoadRunner

Reputation: 26335

You could use a defaultdictdictionary to store the data, with the year as the key, and the data as the values:

from collections import defaultdict

l = [[1982, 1, 108108, 5568], 
     [1982, 2, 64488, 2433], 
     [2007, 498, 4341, 395], 
     [2007, 499, 4328, 274], 
     [2007, 500, 4323, -118]]

# create a dict of lists
data = defaultdict(list)

# go over each sublist in l
for lst in l:

    # the key is the first element in each list
    year = lst[0]

    # add the rest of the list to the value of the key
    data[year] += lst[1:]

>>> print(dict(data))
{1982: [1, 108108, 5568, 2, 64488, 2433], 2007: [498, 4341, 395, 499, 4328, 274, 500, 4323, -118]}

>>> print(data[1982])
[1, 108108, 5568, 2, 64488, 2433]

>>> print(data[2007])
[498, 4341, 395, 499, 4328, 274, 500, 4323, -118]

# here is where you can extract your two lists
>>> print(list(data.values()))
[[1, 108108, 5568, 2, 64488, 2433], [498, 4341, 395, 499, 4328, 274, 500, 4323, -118]]

The benefit of this is that you can have multiple years stored.

Upvotes: 1

coder3521
coder3521

Reputation: 2646

If you have only two elements 1982 & 2007 then you can try below function , or you can add your condition in elif case :

def ListBreak(alist):
    flist,slist =[],[]
    for each in alist:
        if each[0] == 1982:
            flist.append(each)
        else:
            slist.append(each)
    return flist,slist

Here function will return two list that you can simply unpack using :

f,s = ListBreak(yourList)

Hope this helps :)

Upvotes: 0

timgeb
timgeb

Reputation: 78800

>>> l = [[1982, 1, 108108, 5568], [ 1982, 2, 64488, 2433], [ 2007, 498, 4341, 395], [ 2007, 499, 4328, 274], [ 2007, 500, 4323, -118]]
>>> 
>>> result = [[], []]
>>> for sub in l:
...     result[sub[0] == 2007].extend(sub[1:])
... 
>>> result
[[1, 108108, 5568, 2, 64488, 2433], [498, 4341, 395, 499, 4328, 274, 500, 4323, -118]]

First list of result holds the values for 1982, second list holds the values for 2007. Solution assumes you dont' have other years.

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19284

Try the following:

def accessYear(year, data):
    return filter(lambda i: i[0] == year, data)

Upvotes: 1

Related Questions