基于字符串模式从列表创建列表

use*_*463 2 python regex

我有一个类似于下面的示例数据的列表。列表中的每个条目都遵循“source/number_something/”模式。我想创建一个新列表,如下面的输出,其中条目只是“某物”。我想我可以使用 for 循环和字符串拆分,_但后面的一些文本也包括_. 这似乎可以用正则表达式完成,但我不太擅长正则表达式。非常感谢任何提示。

示例数据:

['source/108_cash_total/',
 'source/108_customer/',
 'source/108_daily_units_total/',
 'source/108_discounts/',
 'source/108_employee/',
'source/56_cash_total/',
 'source/56_customer/',
 'source/56_daily_units_total/',
 'source/56_discounts/',
 'source/56_employee/']
Run Code Online (Sandbox Code Playgroud)

输出:

['cash_total',
 'customer',
 'daily_units_total',
 'discounts',
 'employee',
'cash_total',
 'customer/',
 'daily_units_total',
 'discounts',
 'employee']
Run Code Online (Sandbox Code Playgroud)

Jan*_*Jan 6

您可以使用正则表达式:

\d+_([^/]+)
Run Code Online (Sandbox Code Playgroud)

在 regex101.com 上查看演示


Python

import re

lst = ['source/108_cash_total/',
       'source/108_customer/',
       'source/108_daily_units_total/',
       'source/108_discounts/',
       'source/108_employee/',
       'source/56_cash_total/',
       'source/56_customer/',
       'source/56_daily_units_total/',
       'source/56_discounts/',
       'source/56_employee/']

rx = re.compile(r'\d+_([^/]+)')

output = [match.group(1) 
          for item in lst 
          for match in [rx.search(item)] 
          if match]
print(output)
Run Code Online (Sandbox Code Playgroud)

哪个产量

['cash_total', 'customer', 'daily_units_total', 
 'discounts', 'employee', 'cash_total', 'customer',
 'daily_units_total', 'discounts', 'employee']
Run Code Online (Sandbox Code Playgroud)