python - 在Python中使用groupby方法,包含示例

标签 python

尝试使用 groupby 以便我可以将同一天创建的文件分组在一起。当我在这种情况下说同一天时,我指的是 mm/dd/yyyy 中的 dd 部分。因此,如果文件是在 3 月 1 日和 4 月 1 日创建的,则应将它们分组在一起,因为“1”匹配。这是我到目前为止的代码:

#!/usr/bin/python
import os
import datetime
from itertools import groupby

def created_ymd(fn):
  ts = os.stat(fn).st_ctime
  dt = datetime.date.fromtimestamp(ts)
  return dt.year, dt.month, dt.day

def get_files():
  files = []
  for f in os.listdir(os.getcwd()):
    if not os.path.isfile(f): continue
    y,m,d = created_ymd(f)
    files.append((f, d))
  return files

files = get_files()
for key, group in groupby(files, lambda x: x[1]):
  for file in group:
    print "file: %s, date: %s" % (file[0], key)
  print " "

问题是,我收到很多文件,这些文件根据日期分组在一起。但随后我会在同一天看到多个小组。这意味着我可能有 4 个在 17 日创建的文件。稍后我将看到另一组独特的 2 个文件,它们也是在 17 日创建的。我哪里出错了?

最佳答案

groupby() 每次键更改时都会生成一个新组,这意味着您必须首先对数据进行排序才能将所有相似元素分组在一起。试试这个:

files =排序(get_files(), key=(lambda x: x[1]))

然后运行 ​​for 循环。

关于python - 在Python中使用groupby方法,包含示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2564614/

相关文章:

python - 排除统一网格中的端点

python - 如何将 for 循环用作计时器?

python - 从 pandas 数据框中删除值分布极其不均匀的列

python - 当输入的 dtype 为 uint8 时,tf.keras.Model.save 抛出 Not JSON Serialized

python - Django 按顺序连接两个查询集

python - 获取 $_SERVER ['HTTP_USER_AGENT' ] Bottle 中的变量值

python - 使用 Chameleon ZPT 渲染具有任意深度的嵌套元素

python - “NoneType”对象没有属性 'fillna'错误

python - 使用正则表达式过滤字符串中的值

Python - BeautifulSoup html parsing handle gbk encoding poorly - Chinese webscraping 问题