【问题标题】:How to get a list to list a list as a list and not a str?如何获取列表以将列表列为列表而不是 str?
【发布时间】:2018-09-29 10:09:26
【问题描述】:

我正在用 python 3 编写一个程序来组织我的音乐库,但在制作列表时遇到了问题。 我试图迭代列表而不是为每个编解码器编写一个“if”语句,但是当我尝试添加到 listList 中列出的列表时,它称它为字符串而不是列表。 我在最后有打印语句来排除故障。

import os

listList = []
codecList = ('.mp3', '.flac', '.wav') #add codecs here
for c in codecList:
    listList += [c[1:len(c)]+'List']
for L in listList:          
    L = []        
rootDir = '/home/***/Desktop/album'
for dirName, subdirList, fileList in os.walk(rootDir):
    for name in fileList:         
        ext = os.path.splitext(name)[-1].lower()
        for (l, c) in zip(listList, codecList):
            if c == ext:
                l.append(name)
                print(l)
                print(type(l))

最后的打印语句打印:“mp3List\ class 'str'”(如果它当然只找到 1 个 mp3)。 基本上,我想知道如何让 print(type(l)) 最后返回类“list”而不是类“str”,以便我可以使用迭代将文件添加到相应的列表中。

【问题讨论】:

  • 您到底希望for L in listList: L = [] 做什么?

标签: string python-3.x list loops


【解决方案1】:

循环

for L in listList:
    L = []

什么都不做。 L 这里是一个局部变量,它被设置为[],它并不引用listList 中的位置来将该元素设置为[]。如果您希望为 listList 的元素命名,那么您真正想要的可能是字典,而不是列表。这看起来像:

import os

listList = {}
codecList = ('.mp3', '.flac', '.wav') #add codecs here
for c in codecList:
    listList[c[1:len(c)]+'List'] = []
rootDir = '/home/***/Desktop/album'
for dirName, subdirList, fileList in os.walk(rootDir):
    for name in fileList:         
        ext = os.path.splitext(name)[-1].lower()
        for (l, c) in zip(listList, codecList):
            if c == ext:
                listList[l].append(name)

【讨论】:

  • 谢谢!经过一些试验和错误,您的回答得到了它的工作。
  • 我确实缺少对字典的基本理解,看来我有了新目标。
  • @IsaacCrockett 如果对您有帮助,请accept the answer,以便社区可以看到它已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多