2

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

[["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\文件夹","BLAHBLAH\Music"]]

我想要一个看起来像的输出

[[“桌面”、“文档”、“视频”]、[“图片”、“文件夹”、“音乐”]]

我该怎么做呢?这是在 Python 中。我知道您必须将 rfind 与反斜杠一起使用,但我无法遍历嵌套列表以维护该嵌套列表结构

4

6 回答 6

6

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

import os

[[os.path.basename(x) for x in sublist] for sublist in myList]
于 2012-06-07T19:20:37.040 回答
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']]
于 2012-06-07T19:26:50.607 回答
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]
于 2012-06-07T19:23:28.663 回答
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)
于 2012-06-07T19:29:28.750 回答
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,我认为他是在开玩笑。
于 2012-06-07T19:34:08.060 回答
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("/"):])
于 2012-06-07T19:26:43.823 回答