我有以下设置:
text/html
我想复制列表但修剪起始变量,以及除“INFO”段之外的所有内容(即_RANDOM之前和之后的所有内容)。信息每次都不同,RANDOM_STRING_HERE也是如此,但变量是常量。
我怎样才能做到这一点?
澄清一下,我有:
variable = /XXX/XXX/XXX/
list = [/XXX/XXX/XXX/INFO_RANDOM_STRING_HERE.file, etc...]
我想要 列表完整和新列表:
variable = /users/me/folder/
list = [/users/me/folder/file1_001_134543_X5_6MGFS.txt, /users/me/folder/file2_231_234233_Y5_6MGFFAS.txt, etc...]
答案 0 :(得分:1)
您可以在 split()
中使用 list comprehension
:
[x.split(variable)[1].split('_')[0] for x in the_list]
请参阅完整代码:
variable = "/users/me/folder/"
the_list = ["/users/me/folder/file1_001_134543_X5_6MGFS.txt", "/users/me/folder/file2_231_234233_Y5_6MGFFAS.txt"]
print [x.split(variable)[1].split('_')[0] for x in the_list]
输出:
['file1', 'file2']
如果您不想使用 list comprehensions
,而是简单的 for
,我准备了另一个示例(带注释)循环:
variable = "/users/me/folder/"
the_list = ["/users/me/folder/file1_001_134543_X5_6MGFS.txt", "/users/me/folder/file2_231_234233_Y5_6MGFFAS.txt"]
results_list = list()
for full_path in the_list:
_, file_name = full_path.split(variable) # This splits "/users/me/folder/file1_001_134543_X5_6MGFS.txt" into "/users/me/folder/" and "file1_001_134543_X5_6MGFS.txt" so we take the last one as 'file_name'
file_name = file_name.split('_')[0] # This splits e.g. "file1_001_134543_X5_6MGFS.txt" in ["file1", "001", "134543", "X5", "6MGFS.txt"] so we take only the first one, which is in index 0
results_list.append(file_name) # Adding e.g. "file1" to our 'results_list'
print results_list
答案 1 :(得分:1)
variable = "/users/me/folder/"
lst = ["/users/me/folder/file1_001_134543_X5_6MGFS.txt", "/users/me/folder/file2_231_234233_Y5_6MGFFAS.txt"]
lst[:] = [s.replace(variable,"").split("_",1)[0] for s in lst]
print(lst)
输出:
['file1', 'file2']
如果您实际上只是想获取基本名称,可以使用os.path.basename
:
lst = ["/users/me/folder/file1_001_134543_X5_6MGFS.txt", "/users/me/folder/file2_231_234233_Y5_6MGFFAS.txt"]
from os import path
lst[:] = [path.basename(s).split("_",1)[0] for s in lst]
print(lst)
输出:
['file1', 'file2']
答案 2 :(得分:0)
variable = "/users/me/folder/"
list = ["/users/me/folder/file1_001_134543_X5_6MGFS.txt", "/users/me/folder/file2_231_234233_Y5_6MGFFAS.txt"]
length = len(variable)
list = [x[length:] for x in list]