我有一个清单:
var = ["renderPass1", "renderPass2","renderPass3", "renderPassFilter", "renderPassSets"]
如何仅打印 renderPass1、renederPass2 等,我的意思是,仅打印在“renderPass”之后包含数字的成员
我将给出两个答案,因为您的问题不太清楚什么是匹配。
这是因为如果数字的位置不相关:
>>> var = ["renderPass1", "renderPass2","renderPass3", "renderPassFilter", "renderPassSets"]
>>> [x for x in var if any(c.isdigit() for c in x)]
['renderPass1', 'renderPass2', 'renderPass3']
>>>
这是为了如果数字必须在之后"renderPass"
:
>>> from re import search
>>> # I altered the values in here so I could demonstrate
>>> var = ["renderPass1", "renderPass2","renderPass3", "1renderPassFilter", "1renderPassSets"]
>>> [x for x in var if search("renderPass.*\d", x)]
['renderPass1', 'renderPass2', 'renderPass3']
>>>
for value in var:
if value[-1].isdigit(): # check if last char is a number
print value
现在,如果您想测试“renderPass”的字符串
for value in var:
if 'renderPass' in value and value[-1].isdigit()
print value
使用正则表达式查找数字。
查看 python 库:Python: Re。你会想看“\d”。
一个对正则表达式有很大帮助的工具是Txt to Regex。您只需输入要匹配的字符串并使用 GUI 构建正则表达式。然后它在下面为您提供代码。
假设您只需要带有“SomeTextNumber”的模式,您可以这样写
[x for x in var if re.match("\w+\d$", x)]
import re
p = re.compile("[0-9]$")
for s in var:
if p.search(s): print s
根据您对列表中内容的了解程度选择一个。
打印前 3
print var[:3]
打印带有模式renderPass
后跟数字的任何名称
print [name for name in var if name.startswith('renderPass') and name[9].isdigit()]
打印任何带有数字的名称
print [name for name in var if any(ch.isdigit() for ch in name)]
for name in var:
try:
float(name[len("renderPass"):])
print name
except ValueError, er:
# does not have a number after renderPass -> do nothing
pass