首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据月份和年份算法生成文件名列表。

根据月份和年份算法生成文件名列表。
EN

Stack Overflow用户
提问于 2011-02-14 04:19:32
回答 3查看 2K关注 0票数 3

如何以这样的方式列出数字01 to 12 (12个月中每个月一个),使当前月份总是排在最老月份的第一位。换句话说,如果这个数字比现在的月份要高,那是前一年的数字。

例如,02是2011年2月(现在是本月),03是2010年3月,09是2010年9月,而01是2011年1月。在这种情况下,我想要[09, 03, 01, 02]。这就是我决定这一年的原因:

代码语言:javascript
复制
for inFile in os.listdir('.'):
    if inFile.isdigit():
    month = months[int(inFile)]
       if int(inFile) <= int(strftime("%m")):
           year = strftime("%Y")
       else:
           year = int(strftime("%Y"))-1
       mnYear = month + ", " + str(year)

我不知道下一步该怎么做。我在这里该怎么办?

更新:

我想,为了更好的理解,我最好上传整个脚本。

代码语言:javascript
复制
#!/usr/bin/env python

import os, sys
from time import strftime
from calendar import month_abbr

vGroup = {}
vo = "group_lhcb"
SI00_fig = float(2.478)
months = tuple(month_abbr)

print "\n%-12s\t%10s\t%8s\t%10s" % ('VOs','CPU-time','CPU-time','kSI2K-hrs')
print "%-12s\t%10s\t%8s\t%10s" % ('','(in Sec)','(in Hrs)','(*2.478)')
print "=" * 58

for inFile in os.listdir('.'):
    if inFile.isdigit():
        readFile = open(inFile, 'r')
        lines = readFile.readlines()
        readFile.close()

        month = months[int(inFile)]
        if int(inFile) <= int(strftime("%m")):
            year = strftime("%Y")
        else:
            year = int(strftime("%Y"))-1
        mnYear = month + ", " + str(year)

        for line in lines[2:]:
            if line.find(vo)==0:
                g, i = line.split()
                s = vGroup.get(g, 0)
                vGroup[g] = s + int(i)

        sumHrs = ((vGroup[g]/60)/60)
        sumSi2k = sumHrs*SI00_fig
        print "%-12s\t%10s\t%8s\t%10.2f" % (mnYear,vGroup[g],sumHrs,sumSi2k)
        del vGroup[g]

当我运行脚本时,我得到了这个:

代码语言:javascript
复制
[root@serv07 usage]# ./test.py 

VOs               CPU-time  CPU-time     kSI2K-hrs
                  (in Sec)  (in Hrs)      (*2.478)
==================================================
Jan, 2011        211201372     58667     145376.83
Dec, 2010          5064337      1406       3484.07
Feb, 2011         17506049      4862      12048.04
Sep, 2010        210874275     58576     145151.33

正如我在最初的文章中所说的,我希望结果是按以下顺序排列:

代码语言:javascript
复制
Sep, 2010        210874275     58576     145151.33
Dec, 2010          5064337      1406       3484.07
Jan, 2011        211201372     58667     145376.83
Feb, 2011         17506049      4862      12048.04

源目录中的文件如下所示:

代码语言:javascript
复制
[root@serv07 usage]# ls -l
total 3632
-rw-r--r--  1 root root 1144972 Feb  9 19:23 01
-rw-r--r--  1 root root  556630 Feb 13 09:11 02
-rw-r--r--  1 root root  443782 Feb 11 17:23 02.bak
-rw-r--r--  1 root root 1144556 Feb 14 09:30 09
-rw-r--r--  1 root root  370822 Feb  9 19:24 12

我现在给出了更好的画面吗?抱歉,一开始不太清楚。干杯!!

Update @Mark

这是马克的建议的结果:

代码语言:javascript
复制
[root@serv07 usage]# ./test.py 

VOs               CPU-time  CPU-time     kSI2K-hrs
                  (in Sec)  (in Hrs)      (*2.478)
==========================================================
Dec, 2010          5064337      1406       3484.07
Sep, 2010        210874275     58576     145151.33
Feb, 2011         17506049      4862      12048.04
Jan, 2011        211201372     58667     145376.83

如前所述,我正在寻找按以下顺序打印的结果:9月,2010年-> 12月,2010年-> 1月,2011年-> 2月,2011年干杯!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-02-14 16:54:05

除非对列表进行排序,否则不能打印排序列表!我认为修改代码的最简单方法是首先获取文件名,对它们进行排序,然后对排序列表进行操作。通过以元组的形式按该顺序构建列表,排序将自动为您提供正确的顺序。

代码语言:javascript
复制
filelist = []
for inFile in os.listdir('.'):
    if inFile.isdigit():
        if int(inFile) <= int(strftime("%m")):
            year = strftime("%Y")
        else:
            year = int(strftime("%Y"))-1
        filelist.append((year, inFile))
filelist.sort()
for year, inFile in filelist:
    month = months[int(inFile)]
    ...
票数 1
EN

Stack Overflow用户

发布于 2011-02-14 04:50:03

第三次更新:

代码语言:javascript
复制
import os, sys
from time import strftime
from calendar import month_abbr

thismonth = int(strftime("%m"))
sortedmonths = ["%02d" % (m % 12 + 1) for m in range(thismonth, thismonth + 12)]
inFiles = [m for m in sortedmonths if m in os.listdir('.')]

for inFile in inFiles:
    readFile = open(inFile, 'r')
    # [ ... everything else is the same from here (but reindented)... ]

列出理解是比较可取的,但是如果我在2.3中做过的事情不符合犹太教标准,那就试试如下:

代码语言:javascript
复制
inFiles = filter(lambda x: x.isdigit(), os.listdir('.'))
sortedmonths = map(lambda x: "%02d" % (x % 12 + 1), range(thismonth, thismonth + 12))
inFiles = filter(lambda x: x in inFiles, sortedmonths)

第二次更新:

好的,根据您的编辑,我认为最简单的解决方案是:

代码语言:javascript
复制
import os, sys
from time import strftime
from calendar import month_abbr

thismonth = int(strftime("%m"))
inFiles = []
for inFile in os.listdir('.'):
    if inFile.isdigit():
        inFiles.append(inFile)
inFiles.sort(key=lambda x: (int(x) - thismonth - 1) % 12)

for inFile in inFiles:
    readFile = open(inFile, 'r')
    # [ ... everything else is the same from here (but reindented)... ]

这样,主循环以正确的顺序遍历文件。

您还可以用单行理解替换上面的四行循环:

代码语言:javascript
复制
inFiles = [inFile for inFile in os.listdir('.') if inFile.isdigit()]

此外,我建议使用from datetime import datetime,然后使用datetime.now()。它的接口比strftime()好-- datetime.now().month返回一个数字月份( .year.min.second等也是如此,str(datetime.now())提供了一个格式良好的日期时间字符串。

更新:

好的,在做了更多的修改之后,下面是我认为最有效的方法--不管是Jan = 1还是Jan = 0,这都是可行的

代码语言:javascript
复制
>>> themonths = [1, 2, 3, 9]
>>> themonths.sort(key=lambda x: (x - thismonth - 1) % 12)
>>> themonths
[2, 3, 9, 1]

原文:

如果我没听错的话:

代码语言:javascript
复制
>>> thismonth = 1
>>> [m % 12 for m in range(thismonth + 1, thismonth + 13)]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]

或者,如果你只想要几个月,你可以这样做:

代码语言:javascript
复制
>>> thismonth = 1
>>> themonths = [0, 1, 2, 8]
>>> [m % 12 for m in range(thismonth + 1, thismonth + 13) if m % 12 in themonths]
[2, 8, 0, 1]

注意,在这个方案中,Jan = 0 .... Dec = 11。如果您想要Jan = 1,只需将1添加到结果数字(即[m % 12 + 1 for ... if m % 12 + 1 in themonths])。但我认为Jan = 0是一个更好的系统,至少在后端是这样的。

票数 1
EN

Stack Overflow用户

发布于 2011-02-14 06:40:26

你的问题我很难理解。

如果您只想旋转月份的12位数字,因此当前月份的数字是最后一个,则这样做:

代码语言:javascript
复制
>>> def rot_list(l,n):
...    return l[n:]+l[:n]
... 
>>> rot_list(range(1,13),2)
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2]

如果您正在寻找的是目标列表(在您的示例中),则对目标列表进行排序和旋转,使最接近当前月份的列表(由n表示)位于末尾,则这样做:

代码语言:javascript
复制
>>> tar=[1,2,3,9]
>>> n=2
>>> [x for x in range(1,13)[n:]+range(1,13)[:n] if x in tar]
[3, 9, 1, 2]
>>> tar=[3,1,2,9]
>>> [x for x in range(1,13)[n:]+range(1,13)[:n] if x in tar]
[3, 9, 1, 2]

现在,如果您需要该列表具有前导零,并且单个元素是字符串:

代码语言:javascript
复制
>>> nm=[3,9,1,2]
>>> fn=['%02i' % x for x in nm]
>>> fn
['03', '09', '01', '02']

所有这些方法都是有效的,不管Jan是'0‘还是'1’。只需根据约定将range(1,13)的任何引用更改为range(0,12)

编辑

如果我理解了您正在做的事情,下面的代码将有所帮助:

代码语言:javascript
复制
import datetime

def prev_month(year,month,day):
    l=range(1,13)
    l=l[month:]+l[:month]
    p_month=l[10]
    if p_month>month:
        p_year=year-1
    else:
        p_year=year
    return (p_year,p_month,1)

def next_month(year,month,day):
    l=range(1,13)
    l=l[month:]+l[:month]
    p_month=l[0]
    if p_month<month:
        p_year=year+1
    else:
        p_year=year
    return (p_year,p_month,1)

year=2011
month=2
t=(year-1,month,1)
ds=[]
for i in range(1,13):
    print datetime.date(*t).strftime('%m, %y')
    t=next_month(*t)

输出:

代码语言:javascript
复制
02, 10
03, 10
04, 10
05, 10
06, 10
07, 10
08, 10
09, 10
10, 10
11, 10
12, 10
01, 11

只需将文件名的适用格式放入strftime()方法.

希望这就是你要找的..。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4988790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档