繁体   English   中英

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

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

我当前的数据格式为:

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

我想将1982年以来的所有数据放入一个列表,并将2007年以来的所有数据放入另一个列表。

我该怎么做?

请尝试以下操作:

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

您可以使用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]]

这样做的好处是可以存储多年。

>>> 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]]

第一个result列表包含1982年的值,第二个列表包含2007年的值。解决方案假定您没有其他年份。

如果只有两个元素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

这里函数将返回两个列表,您可以使用以下命令简单地将其解压缩:

f,s = ListBreak(yourList)

希望这可以帮助 :)

暂无
暂无

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

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