sansan
Фев. 2, 2011 16:02:09
имеется список Н: Как мне получить из этого списка элементы, которые начинается с “OBpl” и записать их в другой список?
Андрей Светлов
Фев. 2, 2011 16:09:27
А что вы уже пробовали?
Код покажите
Kogrom
Фев. 2, 2011 16:27:03
Для справки: можно воспользоваться startswith.
sansan
Фев. 2, 2011 16:30:32
я пока не знаю как получить элемент вот и спрашиваю… наверно что-то вроде
a=
b=
for x in a:
if x==“OBpl”+???:
b.append(x)
sansan
Фев. 2, 2011 16:33:48
Kogrom а можешь написать этот скриптик?
Kogrom
Фев. 2, 2011 16:39:34
a=["OBpl2", "OBtl", "OBpl3"]
b=[s for s in a if s.startswith("OBpl")]
c=[s for s in a if "OBpl" in s]
truporez
Фев. 2, 2011 16:43:28
Вариант раз:
>>> [item for item in ["OBpl2", "OBtl", "OBpl3"] if item.startswith("OBpl")]
['OBpl2', 'OBpl3']
вариант два:
>>> filter(lambda item: item.startswith("OBpl"),["OBpl2", "OBtl", "OBpl3"])
['OBpl2', 'OBpl3']
alexx11
Фев. 2, 2011 16:43:35
sansanВот парочку вариантов:
l = ["".join([chr(random.randint(97, 122)) for i in range(random.randint(5,10))]) for i in range(100000)]
def f1(sub):
l_sub = len(sub)
return [s for s in l if s[:l_sub] == sub]
def f2(sub):
return [s for s in l if s.startswith(sub)]
А вот результаты:
>>> cProfile.run("f1('abc')")
4 function calls in 0.130 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.130 0.130 0.130 0.130 <stdin>:1(f1)
1 0.000 0.000 0.130 0.130 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
>>> cProfile.run("f2('abc')")
100003 function calls in 0.380 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.210 0.210 0.380 0.380 <stdin>:1(f2)
1 0.000 0.000 0.380 0.380 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
100000 0.170 0.000 0.170 0.000 {method 'startswith' of 'str' objects}
>>>
Kogrom
Фев. 2, 2011 16:45:07
Мой второй вариант некорректный.
alexx11
Фев. 2, 2011 16:45:24
truporez
ЛОЛ
Kogrom
У тебя третий вариант не верный.