什么时候应该使用生成器表达式?什么时候应该在Python中使用列表推导?
# Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
Run Code Online (Sandbox Code Playgroud) 众所周知,有列表理解,比如
[i for i in [1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)
并且有字典理解,比如
{i:j for i, j in {1: 'a', 2: 'b'}.items()}
Run Code Online (Sandbox Code Playgroud)
但
(i for i in (1, 2, 3))
Run Code Online (Sandbox Code Playgroud)
将最终成为一个发电机,而不是tuple理解.这是为什么?
我的猜测是a tuple是不可变的,但这似乎不是答案.
python tuples list-comprehension dictionary-comprehension set-comprehension
我有以下两个功能:
def foo(n=50000):
return sum(i*i for i in range(n)) # just called sum() directly without
def bar(n=50000):
return sum([i*i for i in range(n)]) # passed constructed list to sum()
Run Code Online (Sandbox Code Playgroud)
我希望那foo会跑得更快,bar但我已经检查了ipython,%%timeit那foo时间稍长bar
In [2]: %%timeit
...: foo(50000)
...:
100 loops, best of 3: 4.22 ms per loop
In [3]: %%timeit
...: bar(50000)
...:
100 loops, best of 3: 3.45 ms per loop
In [4]: %%timeit
...: foo(10000000)
...:
1 loops, best of 3: …Run Code Online (Sandbox Code Playgroud) 目前我正在学习生成器和列表理解,并且弄乱了剖析器以查看性能增益,并且在这两个中使用两者中的大量素数的总和数量的混乱.
我可以在生成器中看到:1 genexpr作为累积时间方式比列表对应方式短,但第二行是令我感到困惑的.正在做一个我认为是数字检查的电话是素数,但是不应该是另一个:列表理解中的1个模块?
我在个人资料中遗漏了什么吗?
In [8]: cProfile.run('sum((number for number in xrange(9999999) if number % 2 == 0))')
5000004 function calls in 1.111 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
5000001 0.760 0.000 0.760 0.000 <string>:1(<genexpr>)
1 0.000 0.000 1.111 1.111 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.351 0.351 1.111 1.111 {sum}
In [9]: cProfile.run('sum([number for number in xrange(9999999) if number % 2 == 0])')
3 function calls in 1.123 seconds …Run Code Online (Sandbox Code Playgroud) 是否有一种无需 for 循环的有效方法来比较元组列表中的项目在 Python 中的所有元组中是否相同?
lst_tups = [('Hello', 1, 'Name:'), ('Goodbye', 1, 'Surname:'), ('See you!', 1, 'Time:')]
Run Code Online (Sandbox Code Playgroud)
预期输出是“返回元组索引 1 中项目的所有唯一值”
unique = list()
for i in lst_tups:
item = i[1]
unique.append(item)
set(unique)
Expected Output:
>>
Unique values: [1]
True if all are equal, otherwise False
Run Code Online (Sandbox Code Playgroud)