2012-06-07 53 views
2

讓我們假設我有一個列表,例如:在列表嵌套的某些字符(Python)的前取消一切

[ 「BLAHBLAH \桌面」, 「BLAHBLAH \文檔」, 「BLAHBLAH \西元」],[」 BLAHBLAH \照片管理」, 「BLAHBLAH \文件夾」, 「BLAHBLAH \音樂」]]

而我想的輸出會看起來像

[ 「桌面」, 「文檔」, 「西元」], [「圖片」,「文件夾」,「音樂」]]

我該如何去做呢?這是Python。我知道你將不得不使用rfind反斜槓,但我無法通過嵌套列表迭代以維護嵌套列表結構

+1

你能告訴我們你試過的代碼嗎? – Gerrat

回答

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] 
6

如果您的文件名在myList,這應該做到這一點,並且與平臺無關不同的操作系統使用不同的文件夾分隔符,但os.path模塊負責爲您服務)。

import os 

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

我沒有獲得與Python大氣壓一臺電腦,但下面應該工作:

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("/"):]) 
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']] 
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) 
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誰,我認爲,是在開玩笑。