Skip to main content
 首页 » 编程设计

python之拆分大列表的最快方法

2024年10月01日7yyy_WW

我有一个 DOY 数据列表。该列表几乎有 900,000 个条目。我遇到的问题是数据最初上升到 365,但当我希望它超过 365 时又从 1 开始。例如:

>>> continue_list([140, 141, 145, 270, 365, 365.90, 1, 2, 5, 360]) 
>>> [140, 141, 145, 270, 365, 365.90, 366, 367, 370, 725]  

这是我的尝试:

def continue_list(x): 
    l = [] 
    m = [] 
    for i in x: 
        if math.floor(i) == 1: 
            l = l+ x[x.index(i):] 
            l = list(map(lambda x: x+365, l)) 
            m = m + x[:x.index(i)] 
            new_x = m + l 
    return new_x 

这非常适用于小型列表。但是对于一个有900,000个条目的列表,这是不可行的;我的电脑立即崩溃。有关更快方法的任何提示?

请您参考如下方法:

我会推荐一个生成器:

l = [140, 141, 145, 270, 365, 365.90, 1, 2, 5, 360, 1] 
 
def wrap_at_365(it): 
    # The number of wraps that have been found. 
    wraps = 0 
    it = iter(it) 
    # Get the first item 
    last = next(it) 
    yield last 
    for item in it: 
        # Identify a wrap by checking if the next item is smaller than the previous 
        if item < last: 
            wraps += 1 
        yield item + 365 * wraps 
        last = item 

它可以立即转换为列表:

>>> list(wrap_at_365(l)) 
[140, 141, 145, 270, 365, 365.9, 366, 367, 370, 725, 731] 

在我的电脑上,转换包含 100 万个数字的列表大约需要 0.5 秒。


不过要辨别次数你需要小心。我检查了最后一个项目是否比当前项目大,但是如果它在第 1 年是 100 而下一个项目在第 2 年代表 110 怎么办?那将不会被发现,我实际上不知道如何检测到它。您的数据是否包含更多详细信息?那么闰年呢?