Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Подсчет элементов в словаре
…
Отлично: само продвинутый способ это использовать defaultdict().
print colors[-i]
print colors[len(colors)-i]
Возможно, имелось в виду:
print colors[-i]
print colors[-i - 1]или даже более привычный для сишника синтаксис:
print colors[len(colors)-i]
for i in range(len(colors)-1, -1, -1):
print colors[i]
Группирование элементов списка
itertools.groupby(names, len)
Посдчёт элементов в стловаре
Отлично: само продвинутый способ это использовать defaultdict(). Но вы должны знать как он работает.
d = defaultdict(int) for color in colors: d[color] += 1
>>> d = {'test': 123, 'one':321}
>>> d
{'test': 123, 'one': 321}
>>> len(d)
2
называеться
называется
Подсчет элементов в словаре
for color in colors:
try:
d[color] += 1
except KeyError:
d[color] = 1
for color in colors:
d.setdefault(color, 0)
d[color] += 1
import random
a = [random.randint(1, 10000) for a in range(10000000)]
d = {}
for i in a:
try:
d[i] += 1
except KeyError:
d[i] = 1
d = {}
for i in a:
d[i].setdefault(i, 0)
d[i] += 1
from timeit import timeit
import random
from collections import defaultdict
a = [random.randint(1, 10000) for a in range(10000000)]
def dictionary_setdefault(l, d={}):
for i in l:
d.setdefault(i, 0)
d[i] += 1
def dictionary_keyerror(l, d={}):
for i in l:
try:
d[i] += 1
except KeyError:
d[i] = 1
def defaultdict_simple(l, d=defaultdict(int)):
for i in l:
d[i] += 1
for func in (dictionary_setdefault, dictionary_keyerror, defaultdict_simple):
import sys
sys.stderr.write('Processing {0}\n'.format(func))
print (timeit('import __main__; __main__.{0}(__main__.a)'.format(func.__name__), number=1))
Processing <function dictionary_setdefault at 0x7f16a635c758>
4.41468501091
Processing <function dictionary_keyerror at 0x7f16a635ced8>
2.28980493546
Processing <function defaultdict_simple at 0x7f16a635cf50>
2.04581904411(Python 2.7.5). Python 3.2.5:4.152358055114746
2.3733527660369873
1.9591529369354248
Processing <function dictionary_setdefault at 0x7ff5409bda68>
Processing <function dictionary_keyerror at 0x7ff5409bd9e0>
Processing <function defaultdict_simple at 0x7ff5409bd518>(по всей видимости, stderr буферизуется не по строкам).d = {}
for name in names:
d.setdefault(len(name), []).append(name)
xs = ['zero', 'one', 'two', 'three', 'four']
# плохо
for i in xrange(len(xs)) :
print i, '-->', xs[i]
# ужасно
i = 0
for x in xs :
print i, '-->', xs[i]
i += 1
# хорошо и даже отлично
for i,x in enumerate(xs) :
print i, '-->', xs[i]
show = ['xs[%d]=%s' for i,x in enumerate(xs) if i%2==0] # xs[0]=zero, xs[2]=two, xs[4]=four
look = {x:i for i,x in enumerate(xs)} # для поиска индекса по значению
colors = ['red', 'green', 'blue', 'yellow']
for color in reversed(colors):
print color
colors = ['red', 'green', 'blue', 'yellow']
for color in colors[::-1]:
print color
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated..
for k in d:
k, d[k]
for k, v in d.items():
k, v
%timeit for k in d: k, d[k] 1000 loops, best of 3: 1.33 ms per loop %timeit for k, v in d.items(): k, d 1000 loops, best of 3: 1.92 ms per loop
for i in range(len(colors)):
print colors[i]
Функция должна делать ровно 1 вещь и делать ее хорошо, а в питоне зачастую можно увидеть функцию длиной 40-50 строк которая тем не менее делает 100500 разных вещей которой слабо связаны между собойЧестно, не очень понимаю, причем тут язык. Даже не представляю, какие особенности Питона могут вынудить нарушать этот принцип.
for (auto j = array.begin(), J=array.end(); j!=J; ++j)
if (*j>10)
if (*j == *(j--)*2)
std::cout<<*j<<'\n';
[x[1] for x in zip(array, array[1:]) if x[1] == x[0] * 2 and x[1] > 10]
Но здесь, конечно, двух итераторов не будет только внешне.[x for x_prev, x in zip(xs, xs[1:]) if x > 10 and x == x_prev * 2]
[x for x_prev, x in zip(xs, islice(xs, 1, None)) if x > 10 and x == x_prev * 2]
Пишем красивый идиоматический Python