0

我有一个清单:

var = ["renderPass1", "renderPass2","renderPass3", "renderPassFilter", "renderPassSets"]

如何仅打印 renderPass1、renederPass2 等,我的意思是,仅打印在“renderPass”之后包含数字的成员

4

7 回答 7

2

我将给出两个答案,因为您的问题不太清楚什么是匹配。

这是因为如果数字的位置相关:

>>> 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']
>>>
于 2013-10-29T16:42:54.323 回答
2
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
于 2013-10-29T16:37:39.310 回答
2

使用正则表达式查找数字。

查看 python 库:Python: Re。你会想看“\d”。

一个对正则表达式有很大帮助的工具是Txt to Regex。您只需输入要匹配的字符串并使用 GUI 构建正则表达式。然后它在下面为您提供代码。

于 2013-10-29T16:36:00.957 回答
2

假设您只需要带有“SomeTextNumber”的模式,您可以这样写

[x for x in var if re.match("\w+\d$", x)]
于 2013-10-29T16:47:45.980 回答
1
import re
p = re.compile("[0-9]$")
for s in var:
    if p.search(s): print s
于 2013-10-29T16:49:44.147 回答
1

根据您对列表中内容的了解程度选择一个。

打印前 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)]
于 2013-10-29T16:36:24.960 回答
1
for name in var:
    try:
        float(name[len("renderPass"):])
        print name
    except ValueError, er:
        # does not have a number after renderPass -> do nothing
        pass
于 2013-10-29T16:38:35.813 回答