我正在尝试使用python更改列表中项目的编号,但无论我做什么,它似乎都按数字顺序排列。
假设我在名为items
的列表中有以下项目items = ['1. item1', '2. item2', '3. item3', '4. item4']
这样可视化更容易,所以这是当前的订单
1. item1
2. item2
3. item3
4. item4
从另一个函数我重新排列顺序为:
3. item3
1. item1
4. item4
2. item2
现在,我遇到问题的功能只是将文件重命名为与其位置相对应,现在它将是:
1. item3
2. item1
3. item4
4. item2
问题是数字被放回数字顺序。我的列表项目按特定顺序排列,我希望项目根据其在列表中的位置进行编号
def order(self, directory):
i = 1
#print self.files
for filename in os.listdir(directory):
if filename in self.files: #if the current file in the directory is part of the files list
newfile = re.sub(r'^[0-9][.]',"",filename) #remove the number and decimal from the beginning
os.rename(directory + "/" + filename, directory + "/" + str(i) + ". " + newfile) #rename it with a new number and decimal
i = i + 1
#print newfile
答案 0 :(得分:1)
尝试使用i
- 列表中项目的索引
os.rename(directory + "/" + filename, directory + "/" + str(self.files.index(filename)) + ". " + newfile)
因为我不确定os.listdir
如何命令文件。