【问题标题】:TypeError: list expected at most 1 arguments, got 2TypeError:列表最多需要 1 个参数,得到 2 个
【发布时间】:2020-06-18 22:34:49
【问题描述】:
import os
import sys
listed=[]
for folderName,subfolders,filenames in os.walk('/'):
    for filename in filenames:
        if filename.endswith('.png'):
            listed.append(filename)
            for name in range(len(list(0,10))): 
                print(name)

/我该如何解决这个问题/

【问题讨论】:

  • list(0,10) 是什么意思?这导致了错误
  • 错误信息是准确的。 list 期望 0 或 1 个参数作为可迭代的。见docs.python.org/3/library/stdtypes.html#list
  • 我认为他们的意思是for name in range(len(list[0]), 10):
  • @alec list[0] 也会导致错误。如果您不覆盖 list 名称。
  • 你能解释一下大多数内部for-loop(或你想要的范围)的目的吗?然后我可以告诉如何解决。

标签: python python-3.x list directory append


【解决方案1】:

如果您想打印.png 文件的文件名,这将为您完成:

import os
import sys


listed=[]
for folderName, subfolders, filenames in os.walk('/'):
    for filename in filenames:
        if filename.endswith('.png'):
            listed.append(filename)

    for name in listed: 
        print(name)

但是你得到的TypeError 是因为: for name in range(len(list(0,10))):

您将range 函数传递给end 参数以从0 迭代到end - 1。没关系。但问题是你想在哪里创建列表和长度。 list 函数接受像 tuple 这样的迭代器。

所以你可以这样做:

list((0,10))

但如果您想打印最多十个文件名,只需使用:

listed=[]
for folderName, subfolders, filenames in os.walk('/'):
    for filename in filenames:
        if filename.endswith('.png'):
            listed.append(filename)

    for index in range(10): 
        print(listed[index])

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多