假设我有一个列表,例如:
[["BLAHBLAH\Desktop","BLAHBLAH\Documents","BLAHBLAH\Vids"],["BLAHBLAH\Pics","BLAHBLAH\文件夹","BLAHBLAH\Music"]]
我想要一个看起来像的输出
[[“桌面”、“文档”、“视频”]、[“图片”、“文件夹”、“音乐”]]
我该怎么做呢?这是在 Python 中。我知道您必须将 rfind 与反斜杠一起使用,但我无法遍历嵌套列表以维护该嵌套列表结构
如果您的文件名在 中myList
,则应该这样做,并且也与平台无关(不同的操作系统使用不同的文件夹分隔符,但 os.path 模块会为您处理)。
import os
[[os.path.basename(x) for x in sublist] for sublist in myList]
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']]
您应该使用列表推导:
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]
像这样的东西?
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)
答案的数量很棒。他们都在不同的环境中工作。我只是将其添加到列表中:
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)
我无法使用 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("/"):])