簡體   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