简体   繁体   English

如何在PYTHON中仅提取列表“成员”的一部分?

[英]How do I extract only a part of a list 'member' in PYTHON?

My question is a bit basic, but as I'm a newbie in python (crossed over from GIS), please bear with me. 我的问题有点基本,但是由于我是python的新手(与GIS交叉),请耐心等待。

I have a python list which is based on the files the user inserts - 我有一个基于用户插入的文件的python列表-

for example: inputlist =["c:\\\\files\\\\foobar.shp","c:\\\\files\\\\snafu.shp"] 例如: inputlist =["c:\\\\files\\\\foobar.shp","c:\\\\files\\\\snafu.shp"]

how do I get the file names only (without the path or extesions) into a new list? 如何仅将文件名(不包含路径或扩展名)放入新列表中?

(desired output: ["foobar","snafu"] ) (所需输出: ["foobar","snafu"]

Thanks. 谢谢。

您可以为此使用python的列表推导:

new_list = [ splitext(basename(i))[0] for i in inputlist ]
[os.path.basename(p).rsplit(".", 1)[0] for p in inputlist]
import os.path
extLessBasename = lambda fn: os.path.splitext(os.path.basename(fn))[0]
fileNames = map(extLessBasename, inputlist)

This solution is also help you. 此解决方案也可以为您提供帮助。

import os
inputlist =["/home/anupam/PycharmProjects/DataStructures/LogicalProgram/classvsstatic.py",
            "/home/anupam/PycharmProjects/DataStructures/LogicalProgram/decorators.py"]
filename_list = []
for i in inputlist:
    path_list =i.split('/')
    filename_with_extension = path_list[-1]
    filename_without_extension = os.path.splitext(filename_with_extension)[0]
    filename_list.append(filename_without_extension)

print(filename_list) 

According to windows file path. 根据windows文件路径。 You can split with '//' small change in my code. 您可以在我的代码中以'//'小更改来拆分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM