Найти - Пользователи
Полная версия: получение элементов из списка по началу их названия
Начало » Python для новичков » получение элементов из списка по началу их названия
1 2
sansan
имеется список Н: Как мне получить из этого списка элементы, которые начинается с “OBpl” и записать их в другой список?
Андрей Светлов
А что вы уже пробовали?
Код покажите
Kogrom
Для справки: можно воспользоваться startswith.
sansan
я пока не знаю как получить элемент вот и спрашиваю… наверно что-то вроде
a=
b=
for x in a:
if x==“OBpl”+???:
b.append(x)
sansan
Kogrom а можешь написать этот скриптик?
Kogrom
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
Вариант раз:
>>> [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
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
Мой второй вариант некорректный.
alexx11
truporez
ЛОЛ
Kogrom
У тебя третий вариант не верный.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB