为什么列表理解在 os.walk 函数结果的列表的情况下不起作用?

Why list comprehension doesn't work in case of list whih is result of os.walk function?

在 os.walk 函数的结果中,我得到了这个列表,其中包含文件夹中的文件名:

['tr-02-10-18.pdf', 'tr-02-11-18.pdf', 'tr-02-12-18.pdf', 'tr-03-11-18.pdf', 'tr-03-12-18.pdf', 'tr-04-10-18.pdf', 'tr-04-11-18.pdf', 'tr-04-12-18.pdf']

我的目标是将列表变成那种形式:

['tr/02/10/18.pdf', 'tr/02/11/18.pdf','tr/02/12/18.pdf', 'tr/03/11/18.pdf', 'tr/03/12/18.pdf', 'tr/04/10/18.pdf', 'tr/04/11/18.pdf', 'tr/04/12/18.pdf']

我尝试使用如下所示的代码:

import os
for file_name in os.walk(input()):
    egg1=(str(file_name[-1]))
    egg2= []
    for mark in egg1:
        mark=[i.replace("-","/") for i in mark]
        egg2.append(mark)
print(egg2)

我得到的是这个列表:

[['['], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['0'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['3'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['3'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['0'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [']']]

P.S。这是我的第一个问题,对于任何不一致之处,我们深表歉意

你犯了几个错误:

  1. os.walk() 生成一个包含 3 个元素的元组,即当前目录的路径、文件名列表和目录名列表。您将元组命名为 file_name:

    for file_name in os.walk(input()):
    

    最好将其拆分成单独的组件,所以 for dirpath, dirnames, filenames in os.walk(...):。由于您忽略了前两个参数,因此您还可以使用 for *_, filenames in os.walk(...):

  2. 您将文件名列表变成了一个字符串:

    egg1=(str(file_name[-1]))
    

    file_name[-1] 是文件名列表。你把 list 变成了一个字符串,所以现在你有字符串表示和 [], 逗号字符:

    >>> egg1
    "['tr-02-10-18.pdf', 'tr-02-11-18.pdf', 'tr-02-12-18.pdf', 'tr-03-11-18.pdf', 'tr-03-12-18.pdf', 'tr-04-10-18.pdf', 'tr-04-11-18.pdf', 'tr-04-12-18.pdf']"
    

    然后您从上面的字符串中取出每个单独的字符,并将破折号替换为斜杠。不要把列表变成字符串,直接遍历列表。

  3. egg2 列表替换为每个目录的新空列表。在 os.walk() 循环 之前 创建列表。

  4. 您将每个 str.replace() 调用的结果放入一个包含单个元素的新列表中,然后将该列表附加到 egg2 列表中。不要添加更多列表。

此代码有效:

result = []

for *_, filenames in os.walk(input()):
    for filename in filenames:
        replaced = filename.replace('-', '/')
        result.append(replaced)

这可以组合成一个列表理解:

result = [f.replace('-', '/') for *_, fs in os.walk(input()) for f in fs]