我正在Python上开发我的第一个“Hello World”!很久以前我是Visual Basic程序员
我尝试使用Namedtuple集合,如下所示:
#!/usr/bin/env python3
import collections
#Tipo da colecao
File = collections.namedtuple('File',['abspath' ,'basename','filextention','filetype'])
Files = []
Files.append(File('/home/user/teste1.txt', 'teste1.txt','txt',''))
Files.append(File('/home/user/teste2.txt', 'teste2.txt','txt',''))
Files.append(File('/home/user/teste3.txt', 'teste2.txt','txt',''))
for lCtd in range(0,len(Files)):
print(Files[lCtd].abspath,Files[lCtd].basename,Files[lCtd].filextention)
for lCtd in range(0,len(Files)):
#>>>>>How can I do this?!<<<<<
Files[lCtd].filetype = 'A'
如果有一个最好的方法来做这件事(或所有的代码),我洗耳恭听
非常感谢
似乎您真正想要的是定义自己的类,如下所示:
命名元组很有用,但它们是不可变的:它们的属性在创建后不能更改。如果您想要一个类似的方便易变的数据保持器,那么您可能对data classes感兴趣,只要您使用的是Python 3.7或更新版本
请注意,在列表(或任何序列)中循环的更具python风格的方法是不依赖
len
和索引,而只是在项目本身中循环综上所述,如果您正在寻找一种处理文件的简单方法,例如获取文件名和扩展名,那么您可能还应该看看Pathlib
p.S.
file
是Python2中的一个内置项,许多编辑器可能仍然会突出显示它本身,但在Python3中用作变量/类名应该是不错的相关问题 更多 >
编程相关推荐