2

我有这样的场景:

a = ["file1","file2","file3","file1","file2","file1","file5"]
set_flag = 0
for i in range (len(a)):
    file_name = '%s.txt' %(a[i])
    file_write = open('%s'%(file_name),'w')

以上工作并写入文件。但是,我想包含一个逻辑,即使某些文件名在上面的列表中出现多次,file_write 也应该只发生一次。不应有多个文件写入。例如,如果 file1 出现 4 次,它应该只被写入一次。这样,set_flag 应该设置为“1”,这样如果我尝试在代码中的任何位置写入 file1,它应该绕过文件写入。任何想法如何实现这一点并设置这样的标志..?

4

3 回答 3

4

使用set(),它只存储一个项目的单个副本:

>>> a=["file1","file2","file3","file1","file2","file1","file5"]
>>> set(a)
set(['file3', 'file2', 'file1', 'file5'])

对于您的代码,这也将保持顺序。:

a=["file1","file2","file3","file1","file2","file1","file5"]
seen=set()
for file in a:               #you can iterate over a list itself
    if file not in seen:     #if file is not in the set then write 
       file_name= '%s.txt' %(file)
       file_write= open('%s'%(file_name),'w')
       seen.add(file)  #add file to seen
于 2013-05-03T10:49:37.510 回答
1

集合是个好主意,因此您只需遍历列表中的唯一文件名。另外,不要使用range(len(...))和其他一些清理:

a = ["file1","file2","file3","file1","file2","file1","file5"]
set_flag = 0
for file_name in set(a):
    file_write = open(file_name + '.txt', 'w')
于 2013-05-03T10:59:39.643 回答
1

如果由于某种原因需要创建输出文件的顺序,那么OrderedDict可以使用 an(在 2.7+ 中):

for fname in OrderedDict.fromkeys(a):
    with open(fname, 'w') as fout:
        pass
于 2013-05-03T11:04:19.037 回答