У меня есть список имен файлов:
names = ['aet2000','ppt2000', 'aet2001', 'ppt2001']
Пока я нашел некоторые функции, которые могут работать с grep символьными строками, я не понял, как grep все элементы списка.
например, я хотел бы:
grep(names,'aet')
и получим:
['aet2000','aet2001']
Уверен, что это не слишком сложно, но я новичок в 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
Запуск фильтра (lambda x: 'aet' в 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
Несмотря на то, что tifnames - это список строк символов:
type(tifnames[1])
<type 'str'>
Вы, ребята, видите, что здесь происходит? Еще раз спасибо!