简体   繁体   English

如何将一个列表分为两个不同的列表?(Python2.7)

[英]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. 我想将1982年以来的所有数据放入一个列表,并将2007年以来的所有数据放入另一个列表。

How would I do this? 我该怎么做?

Try the following: 请尝试以下操作:

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

You could use a defaultdict dictionary to store the data, with the year as the key, and the data as the values: 您可以使用defaultdict词典存储数据,以年份为键,以数据为值:

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. 这样做的好处是可以存储多年。

>>> 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. 第一个result列表包含1982年的值,第二个列表包含2007年的值。解决方案假定您没有其他年份。

If you have only two elements 1982 & 2007 then you can try below function , or you can add your condition in elif case : 如果只有两个元素1982和2007,则可以尝试使用以下函数,或者可以在elif情况下添加条件:

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 :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM