【问题标题】:Replace two nested loops with a dictionary comprehension用字典理解替换两个嵌套循环
【发布时间】:2012-04-23 10:13:31
【问题描述】:

有没有办法用字典理解替换下面的代码?

d = {}

for i in xrange(A):
    for j in xrange(B):

         d[(i, j)] = f(i, j)

如果这有什么不同的话,我正在使用 Python2.7。

【问题讨论】:

    标签: python dictionary list-comprehension


    【解决方案1】:
    d = {(i,j):f(i,j) for i in xrange(A) for j in xrange(B)}
    

    【讨论】:

      【解决方案2】:

      itertools.product替换嵌套循环通常是个好主意:

      from itertools import product
      d = { p: f(*p) for p in product(range(A), range(B))}
      

      【讨论】:

        猜你喜欢
        • 2015-10-13
        • 2017-03-09
        • 2021-06-03
        • 1970-01-01
        • 2019-01-24
        • 2021-10-03
        • 2017-07-22
        • 2022-06-15
        相关资源
        最近更新 更多