删除嵌套列表中某些字符之前的所有内容(Python)

时间:2012-06-07 19:17:22

标签: python list

假设我有一个列表,例如:

[[ “BLAHBLAH \桌面”, “BLAHBLAH \文件”, “BLAHBLAH \西元”],[ “BLAHBLAH \照片管理”, “BLAHBLAH \文件夹”, “BLAHBLAH \音乐”]]

我想要一个看起来像

的输出

[[ “桌面”, “文档”, “西元”],[ “照片管理”, “文件夹”, “音乐”]]

我该怎么做?这是在Python中。我知道你必须使用带有反斜杠的rfind,但我无法迭代嵌套列表以维护嵌套列表结构

6 个答案:

答案 0 :(得分:6)

如果您的文件名在myList中,则应该这样做,并且也可以独立于平台(不同的操作系统使用不同的文件夹分隔符,但os.path模块会为您处理)。

import os

[[os.path.basename(x) for x in sublist] for sublist in myList]

答案 1 :(得分:3)

lis=[["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\Folder","BLAHBLAH\Music"]]

def stripp(x):
    return x.strip('BLAHBLAH\\')

lis=[list(map(stripp,x)) for x in lis]
print(lis)                   

<强>输出:

[['Desktop', 'Documents', 'Vids'], ['Pics', 'Folder', 'Music']]

答案 2 :(得分:2)

您应该使用列表推导:

NestedList = [["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\Folder","BLAHBLAH\Music"]]
output = [[os.path.basename(path) for path in li] for li in NestedList]

答案 3 :(得分:1)

这样的东西?

from unittest import TestCase
import re


def foo(l):
    result = []
    for i in l:
        if isinstance(i, list):
            result.append(foo(i))
        else:
            result.append(re.sub('.*\\\\', '', i))
    return result


class FooTest(TestCase):
    def test_foo(self):
        arg = ['DOC\\Desktop', 'BLAH\\FOO', ['BLAH\\MUSIC', 'BLABLA\\TEST']]
        expected = ['Desktop', 'FOO', ['MUSIC', 'TEST']]
        actual = foo(arg)
        self.assertEqual(expected, actual)

答案 4 :(得分:1)

答案的数量非常多。它们都在不同的环境中工作。我只是将其添加到列表中:

outer = [["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],
         ["BLAHBLAH\Pics","BLAHBLAH\Folder","BLAHBLAH\Music"]]

purged = [ [ item[ item.find("\\")+1: ]
             for item in inner ]
           for inner in outer ]

荣誉(和+1)到

  • @Junuxx,他是第一个使用文件名解决方案的人,
  • 到@Ashwini Chaudary,如果这些不是文件名,他们会获得更通用的解决方案,并且
  • 到@mfusennegger,我认为,他正在开个玩笑。

答案 5 :(得分:0)

我无法使用python atm访问计算机,但以下内容应该可以使用:

List=[["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\Folder","BLAHBLAH\Music"]]
final=[]
for varv in List:
    x=varv
    for sub_val in x:
        final.append(sub_val[sub_val.find("/"):])