从满足某些条件的列表中删除某些元素

2024-06-07 11:48:05 发布

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

我有一个包含一些文件名(位置)的列表,我要做的是从列表位置中删除所有元素。你知道吗

条件:若文件名以排除列表中的任何字符串开头,则不要打印该文件名。你知道吗

locations = ['/data/mybackup/data/fil1',
            '/data/mybackup/data/fil2', 
            '/data/mybackup/data/fil3', 
            '/data/mybackup/song/fil1', 
            '/data/mybackup/song/fil2',
            '/data/mybackup/song/fil3', 
            '/data/archive/song/fil1', 
            '/data/archive/song/fil2', 
            '/data/archive/song/fil3', 
            '/data/archive/data/fil1', 
            '/local/archive/data/fil2', 
            '/local/archive/data/fil3',
            '/ebboks/wordpress/fil1', 
            '/ebooks/wordpress/fil2', 
            '/ebooks/wordpress/fil3']

excludes = [  '/data/archive/', '/data' , '/ebooks/'   ]

for location in locations:
  for exclude in excludes:
    if not location.startswith(exclude):
      print(location)
    break      

结果:

/data/mybackup/data/fil1
/data/mybackup/data/fil2
/data/mybackup/data/fil3
/data/mybackup/song/fil1
/data/mybackup/song/fil2
/data/mybackup/song/fil3
/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1
/ebooks/wordpress/fil2
/ebooks/wordpress/fil3     

我的结果仍然有以'/data'开头的文件名

我的代码怎么了?你知道吗


Tags: 列表datasong文件名localwordpresslocationarchive
3条回答

因为location就是"/data/mybackup/data/fil1"exclude就是"/data/archive"location变量不是以"/data/archive"开头的。你知道吗

由于在excludes列表中有一个"/data"值,因此不需要放置另一个以"/data"开头的路径。因此,如果定义excludes = ["/data", "/ebooks"],就不会有问题。你知道吗

Condition: do not print the file name if it starts with the any of the strings in the excludes list.

使用all()函数:

for location in locations:
    if all(not location.startswith(e) for e in excludes):
        print(location)

输出:

/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1

str.startswith接受要检查的tuple个参数,这样就避免了额外的循环检查和有关排序比较的问题,因此可以使用:

exc = tuple(excludes)
# Or start with: excludes = ('/data/archive/', '/data' , '/ebooks/') instead
for location in locations:
    if not location.startswith(exc):
        print(location)

这给了你:

/local/archive/data/fil2
/local/archive/data/fil3
/ebboks/wordpress/fil1

相关问题 更多 >

    热门问题