gpt4 book ai didi

python - 使用 Python 创建列表列表

转载 作者:行者123 更新时间:2023-11-28 22:43:00 25 4
gpt4 key购买 nike

我有一个列表,其中包含从 2003 年到 2005 年的十二月到二月的年和日。我想将这个列表分成列表列表以保存从十二月到二月的年日:

a = ['2003337', '2003345', '2003353', '2003361', '2004001', '2004009', '2004017', '2004025', '2004033', '2004041', '2004049', '2004057', '2004337', '2004345', '2004353', '2004361', '2005001', '2005009', '2005017', '2005025', '2005033', '2005041', '2005049', '2005057']

输出应该是这样的:

b = [['2003337', '2003345', '2003353', '2003361', '2004001', '2004009', '2004017', '2004025', '2004033', '2004041', '2004049', '2004057'] ['2004337', '2004345', '2004353', '2004361', '2005001', '2005009', '2005017', '2005025', '2005033', '2005041', '2005049', '2005057']]

然后遍历列表的每个列表。我可以使用 even splitting但有可能错过年。所以最好不要平分。有什么建议吗?

最佳答案

转换为日期时间,然后按最近结束的年份分组。

import datetime
import itertools

#convert from a "year-day" string to a datetime object
def datetime_from_year_day(s):
year = int(s[:4])
days = int(s[4:])
return datetime.datetime(year=year, month=1, day=1) + datetime.timedelta(days=days-1)

#returns the year whose end is closest to the date, whether in the past or future
def nearest_year_end(d):
if d.month <= 6:
return d.year-1
else:
return d.year

a = ['2003337', '2003345', '2003353', '2003361', '2004001', '2004009', '2004017', '2004025', '2004033', '2004041', '2004049', '2004057', '2004337', '2004345', '2004353', '2004361', '2005001', '2005009', '2005017', '2005025', '2005033', '2005041', '2005049', '2005057']

result = [list(v) for k,v in itertools.groupby(a, lambda s: nearest_year_end(datetime_from_year_day(s)))]
print result

结果:

[['2003337', '2003345', '2003353', '2003361', '2004001', '2004009', '2004017', '2004025', '2004033', '2004041', '2004049', '2004057'], ['2004337', '2004345', '2004353', '2004361', '2005001', '2005009', '2005017', '2005025', '2005033', '2005041', '2005049', '2005057']]

关于python - 使用 Python 创建列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31293610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com