从list - python中删除已定义的字符串

时间:2016-02-11 10:04:59

标签: python list indexing split

foo = '/input/directory/'
faa = ['/input/directory/file1.txt', '/input/directory/file2.txt']

我需要从我的列表(faa)和文件扩展名中删除目录名称(即foo),只留下

bar = ['file1', 'file2']

7 个答案:

答案 0 :(得分:4)

使用map

bar = map(lambda x: '.'.join(x.replace(foo, '').split('.')[:-1]), faa)

答案 1 :(得分:1)

试;

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

答案 2 :(得分:1)

也许:

try this. 

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }

答案 3 :(得分:1)

foo = '/input/directory/'
faa = ['/input/directory/file1.txt', '/input/directory/file2.txt']

import os.path

bar = [os.path.splitext(path.replace(foo, ''))[0]
       for path in faa]
print(bar)

或者没有foo:

faa = ['/input/directory/file1.txt', '/input/directory/file2.txt']

from os.path import basename, splitext
bar = [splitext(basename(path))[0]
       for path in faa]
print(bar)

答案 4 :(得分:0)

您可以执行以下操作:

import os

foo = '/input/directory/'
faa = ['/input/directory/file1.txt', '/input/directory/file2.txt', '/not/matching/foo/file3.txt']   

faa = [os.path.splitext(os.path.split(f)[1])[0] if f.startswith(foo) else f for f in faa]   
print faa

这会给你以下列表:

['file1', 'file2', '/not/matching/foo/file3.txt']

如果您总是想要文件名,那么:

import os

foo = '/input/directory/'
faa = ['/input/directory/file1.txt', '/input/directory/file2.txt', '/not/matching/foo/file3.txt']   

faa = [os.path.splitext(os.path.split(f)[1])[0] for f in faa]   
print faa

,并提供:

['file1', 'file2', 'file3']

答案 5 :(得分:0)

您可以执行以下操作:

SamplerState sam3DPoint
{
    Filter = MIN_MAG_MIP_POINT;
    AddressU = Border;
    AddressV = Border;
    AddressW = Border;
    BorderColor = float4(0, 0, 0, 0);
};

答案 6 :(得分:0)

您可以使用re模块和re.findall来实现(?<=)字符串foo后面的积极外观,以及带{} extension的{​​{1}}到字符串的末尾:

res = [re.findall('(?<={}).+(?=[.].*$)'.format(foo), elem)[0] for elem in faa]

print(res)
['file1', 'file2']

注意:您可以使用regex101.com检查regex表达式