TypeError:列表最多需要1个参数,得到2个

2024-09-28 23:26:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

/我希望此脚本查找所有.png文件,但最多只能打印10个,但运行脚本时会出现错误:“TypeError:list最多需要1个参数,Get 2”我如何修复此问题


Tags: nameinimport脚本forpngossys
1条回答
网友
1楼 · 发布于 2024-09-28 23:26:16

如果要打印.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))

但如果您想打印多达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])

相关问题 更多 >