相关疑难解决方法(0)

生成器表达式与列表理解

什么时候应该使用生成器表达式?什么时候应该在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)

python list-comprehension generator

390
推荐指数
7
解决办法
13万
查看次数

为什么Python中没有元组理解?

众所周知,有列表理解,比如

[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

289
推荐指数
7
解决办法
9万
查看次数

带/不带列表理解的python函数调用

我有以下两个功能:

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,%%timeitfoo时间稍长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)

python python-3.x

12
推荐指数
1
解决办法
534
查看次数

Python中的Generators vs List Comprehension性能

目前我正在学习生成器和列表理解,并且弄乱了剖析器以查看性能增益,并且在这两个中使用两者中的大量素数的总和数量的混乱.

我可以在生成器中看到: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)

python profiling list-comprehension generator

6
推荐指数
1
解决办法
999
查看次数

python 比较元组列表中项目的有效方法

是否有一种无需 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)

python data-structures

1
推荐指数
1
解决办法
106
查看次数