Note that there are some explanatory texts on larger screens.

plurals
  1. POGrep on elements of a list
    text
    copied!<p>I have a list of files names:</p> <pre><code>names = ['aet2000','ppt2000', 'aet2001', 'ppt2001'] </code></pre> <p>While I have found some functions that can work to grep character strings, I haven't figured out how to grep all elements of a list.</p> <p>for instance I would like to: </p> <pre><code>grep(names,'aet') </code></pre> <p>and get:</p> <pre><code>['aet2000','aet2001'] </code></pre> <p>Sure its not too hard, but I am new to Python</p> <hr> <p><B> update </B> The question above apparently wasn't accurate enough. All the answers below work for the example but not for my actual data. Here is my code to make the list of file names:</p> <pre><code>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 </code></pre> <p>Running filter(lambda x:'aet' in x,tifnames) or the other answers return:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#89&gt;", line 1, in &lt;module&gt; func(tifnames,'aet') File "&lt;pyshell#88&gt;", line 2, in func return [i for i in l if s in i] TypeError: argument of type 'int' is not iterable </code></pre> <p>Despite the fact that tifnames is a list of character strings:</p> <pre><code>type(tifnames[1]) &lt;type 'str'&gt; </code></pre> <p>Do you guys see what's going on here? Thanks again!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload