【问题标题】:Python creating specific list from another listPython从另一个列表创建特定列表
【发布时间】:2015-06-28 22:08:39
【问题描述】:

学习python遇到如下问题。我已经有一些带有整数的列表(例如initial_list)。然后我尝试使用以下数字模式创建列表(例如result):

result[len(result) - 1] = 1
result[i] = result[i + 1] * initial_list[i]

例子:

initial_list = [2, 2, 2, 2, 3, 2, 2]
result = [192, 96, 48, 24, 12, 4, 2, 1]

这是我的第一个实现:

import numpy as np
initial_list = [2, 2, 2, 2, 3, 2, 2]
result = [1]
for number in reversed(initial_list):
    result.append(result[-1] * number)
result = np.array(result[::-1])

这是我的第二个实现:

import numpy as np
initial_list = [2, 2, 2, 2, 3, 2, 2]
result = np.ones(len(initial_list) + 1)
for i, number in enumerate(reversed(initial_list)):
    result[len(result) - i - 2] = result[len(result) - i - 1] * number

我猜第二个要好得多,因为它不包含附加方法和使用具体大小初始化列表。 result = np.ones(len(initial_list) + 1) 还包含不正确的浮点数。我想知道这个算法的实现是否有更简单的版本。

在该算法之后,我正在创建OrderedDict:

from collections import OrderedDict
ordered_dict = OrderedDict(zip(other_list, result))

也许我可以在为O(1)“on fly”创建OrderedDict 过程中反转result 列表,就像reversed 工作在for 循环中,这样我就可以简化上面的算法。

【问题讨论】:

  • 算法应该做什么?
  • @PadraicCunningham 它应该使用上述模式从初始列表创建列表:result[len(result) - 1] = 1, result[i] = result[i + 1] * initial_list[i]
  • 我认为列表理解是个好主意,但我无法弄清楚你的算法。例如,result[len(result) - 1] = 1 只有在 result 中有一些数据时才有意义。 result 开头是什么样子的?
  • @Quill 也许我理解错了?我专门阅读了 “我想知道是否有一个更简单的算法实现版本。” 部分,并认为它在那里更有意义,因为它似乎是代码优化的问题。在on-topic section 中,似乎说“最佳实践和设计模式使用” 是主题“对您项目中特定工作代码的反馈”。显然,你会比我更了解什么是题外话,但我就是不明白你为什么这么认为。
  • 看来您是对的,感谢您阅读主题部分和帮助中心指南。 OP,如果您愿意,请随时将其带到 Code Review 中。

标签: python list for-loop reverse enumerate


【解决方案1】:

如果numpy 是一个选项,您可以使用cumprod:

import numpy as np

initial_list = [2, 2, 2, 2, 3, 2, 2]

>> np.append(np.cumprod(initial_list[:: -1])[:: -1], [1])
array([192,  96,  48,  24,  12,   4,   2,   1])

【讨论】:

  • numpy 绝对是一个选择,他们正在使用它;)
  • @PadraicCunningham :-) 没错。谢谢!
  • @AmiTavory 在一行中,这就是我所需要的。谢谢!
【解决方案2】:

您可以使用itertools.accumulate 和operator.mul

>>> from itertools import accumulate
>>> from operator import mul
>>> a = [2, 2, 2, 2, 3, 2, 2]
>>> list(accumulate(reversed(a + [1]), mul))[::-1]
[192, 96, 48, 24, 12, 4, 2, 1]

【讨论】:

  • itertools + operator 的完美结合。
【解决方案3】:

你为什么不能这样做

result = [0] * len(initial_list)
result[-1] = 1
for i in xrange(len(result) - 2, -1, -1):
  result[i] = result[i + 1] * initial_list[i]

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2020-05-07
    相关资源
    最近更新 更多