Найти - Пользователи
Полная версия: Как проверить наличие словаря в кортеже?
Начало » Python для новичков » Как проверить наличие словаря в кортеже?
1 2 3 4
MiK

Немного поправлю пример для FishHook, а то в попыхах строчку забыл, а он потом сам-же меня укорять будет:
def f(tup):
	c = 0
	a = (isinstance(d, dict) for d in tup)
	while a:
		c += 1
		if next(a):
			print(c)
			return True
Shaman
Посмотрите внимательнее на пример FishHook.
MiK
Shaman
Думал, что тупой. Посмотрел, разобрал. Вижу, что человек запутался, с кем не бывает. Я тоже строчку в попыхах забыл.
Shaman
import timeit
 
print timeit.timeit('True in (isinstance(d, dict) for d in a)', 'a = [{}] + [0] * 1000')
print timeit.timeit('dict in map(type, a)', 'a = [{}] + [0] * 1000')
print timeit.timeit('dict_in_tuple(a)', '''
def dict_in_tuple(tpl):
    for i in tpl:
        if isinstance(i, dict):
            return True
    return False
a = [{}] + [0] * 1000''')
CPython:
1.13017768686
77.060392235
0.511236281781
PyPy:
0.0639355380552
7.07967514163
0.0076938339856
При замее map на imap
print timeit.timeit('dict in imap(type, a)', '''
from itertools import imap
a = [{}] + [0] * 1000''')
CPython:
0.510152251704
PyPy:
0.119754748351
Итого, логика оптимизации интерпретатором in неочевидна.
py.user.next
Shaman
1.13017768686
77.060392235
0.511236281781

[guest@localhost ~]$ python3 -m timeit 'dict in map(type, (1, 2, {}, 3, 4))'
1000000 loops, best of 3: 0.948 usec per loop
[guest@localhost ~]$
[guest@localhost ~]$ python3 -m timeit 'True in (isinstance(d, dict) for d in (1, 2, {}, 3, 4))'
100000 loops, best of 3: 3.07 usec per loop
[guest@localhost ~]$
[guest@localhost ~]$ python3 -m timeit -s '
def dict_in_tuple(tpl):
for i in tpl:
if isinstance(i, dict):
return True
return False
' 'dict_in_tuple((1, 2, {}, 3, 4))'
1000000 loops, best of 3: 1.74 usec per loop
[guest@localhost ~]$
Shaman
При плохом случае разброд и шатание продолжается:
import timeit
 
print timeit.timeit('True in (isinstance(d, dict) for d in a)', 'a = [0] * 100 + [{}]')
print timeit.timeit('dict in imap(type, a)', '''
from itertools import imap
a = [0] * 100 + [{}]''')
print timeit.timeit('dict_in_tuple(a)', '''
def dict_in_tuple(tpl):
    for i in tpl:
        if isinstance(i, dict):
            return True
    return False
a = [0] * 100 + [{}]''')
CPython:
47.0908015237
10.0060226744
35.0324400811
PyPy:
1.15349395509
0.303581019596
0.30440633638
Shaman
py.user.next, до третьего у меня руки не дошли, ибо далёк он от меня.
py.user.next
Shaman
При плохом случае разброд и шатание продолжается:
[guest@localhost ~]$ python3 -m timeit 'dict in map(type, (1, 2, 3, 4, {}))'
1000000 loops, best of 3: 1.19 usec per loop
[guest@localhost ~]$
[guest@localhost ~]$ python3 -m timeit 'True in (isinstance(d, dict) for d in (1, 2, 3, 4, {}))'
100000 loops, best of 3: 4.26 usec per loop
[guest@localhost ~]$
[guest@localhost ~]$ python3 -m timeit -s '
def dict_in_tuple(tpl):
for i in tpl:
if isinstance(i, dict):
return True
return False
' 'dict_in_tuple((1, 2, 3, 4, {}))'
100000 loops, best of 3: 2.57 usec per loop
[guest@localhost ~]$
Shaman
Плохой для третьего (производительность стенда та же)
import timeit
 
print(timeit.timeit('True in (isinstance(d, dict) for d in a)', 'a = [0] * 100 + [{}]'))
print(timeit.timeit('dict in map(type, a)', 'a = [0] * 100 + [{}]'))
print(timeit.timeit('dict_in_tuple(a)', '''
def dict_in_tuple(tpl):
    for i in tpl:
        if isinstance(i, dict):
            return True
    return False
a = [0] * 100 + [{}]'''))
CPython:
52.93401057773885
11.18879827034128
38.54579610142588
PyPy:
1.3422986398095187
0.30182305208133786
0.32124536454199615
MiK
Очень любопытное исследование. Однако буггурт был не в этом, а в том, что было написано большими, в полэкрана буквами.

Ну и от себя: “С точки зрения целостности кода, писать отдельную функцию вместо выражения, если она больше нигде не будет использоваться или будет использоваться очень редко, - не айс”.

По какой же причине инструкция “in” столь неоднозначно работает, я не знаю.
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