Grep列表的元素

mma*_*123 29 python grep list

我有一个文件名列表:

names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
Run Code Online (Sandbox Code Playgroud)

虽然我找到了一些可以用来grep字符串的函数,但我还没弄清楚如何grep列表中的所有元素.

比如我想:

grep(names,'aet')
Run Code Online (Sandbox Code Playgroud)

得到:

['aet2000','aet2001']
Run Code Online (Sandbox Code Playgroud)

当然不是太难,但我是Python新手


更新 上面的问题显然不够准确.下面的所有答案都适用于示例,但不适用于我的实际数据.这是我的代码来制作文件名列表:

years = range(2000,2011)
months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
variables = ["cwd","ppt","aet","pet","tmn","tmx"]     #  *variable name*  with wildcards   
tifnames = list(range(0,(len(years)*len(months)*len(variables)+1)  ))
i = 0
for variable in variables:
   for year in years:
      for month in months:
         fullname = str(variable)+str(year)+str(month)+".tif"
         tifnames[i] = fullname
         i = i+1 
Run Code Online (Sandbox Code Playgroud)

运行过滤器(lambda x:'aet'in x,tifnames)或其他答案返回:

Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    func(tifnames,'aet')
  File "<pyshell#88>", line 2, in func
    return [i for i in l if s in i]
TypeError: argument of type 'int' is not iterable
Run Code Online (Sandbox Code Playgroud)

尽管tifnames是一个字符串列表:

type(tifnames[1])
<type 'str'>
Run Code Online (Sandbox Code Playgroud)

你们看到这里发生了什么事吗?再次感谢!

Ash*_*ary 46

用途filter():

>>> names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
>>> filter(lambda x:'aet' in x, names)
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

regex:

>>> import re
>>> filter(lambda x: re.search(r'aet', x), names)
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

在Python 3中,过滤器返回一个迭代器,因此可以对其进行列表调用list().

>>> list(filter(lambda x:'aet' in x, names))
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

否则使用list-comprehension(它将在Python 2和3中都有效:

>>> [name for name in names if 'aet' in name]
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是lambda arg声明和函数定义之间可以有一个空格(例如:``lambda x:'aet'在x`中) (2认同)

mrc*_*mpe 10

试试吧.它可能不是所有代码的"最短",但对于试图学习python的人来说,我认为它教的更多

names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
found = []
for name in names:
    if 'aet' in name:
       found.append(name)
print found
Run Code Online (Sandbox Code Playgroud)

产量

['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

编辑:更改为生成列表.

也可以看看:

如何使用Python找出列表中以元音开头的单词?


roo*_*oot 8

>>> names = ['aet2000', 'ppt2000', 'aet2001', 'ppt2001']
>>> def grep(l, s):
...     return [i for i in l if s in i]
... 
>>> grep(names, 'aet')
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

正则表达式版本,更接近grep,虽然在这种情况下不需要:

>>> def func(l, s):
...     return [i for i in l if re.search(s, i)]
... 
>>> func(names, r'aet')
['aet2000', 'aet2001']
Run Code Online (Sandbox Code Playgroud)

  • 请[永远不要使用 l(小写“ell”)作为变量名](https://www.python.org/dev/peps/pep-0008/#names-to-avoid)! (2认同)