簡體   English   中英

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

[英]Remove everything before certain character in nested lists (Python)

讓我們假設我有一個列表,如:

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

我想要一個看起來像的輸出

[ “桌面”, “文檔”, “西元”],[ “照片管理”, “文件夾”, “音樂”]

我該怎么做呢? 這是在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)來

  • @Junuxx是第一個使用文件名解決方案的人,
  • 到@Ashwini Chaudary,如果這些不是文件名,那么他們會獲得更通用的解決方案
  • @mfusennegger,我認為,他正在開個玩笑。

我沒有訪問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("/"):])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM