python - 重写代码以使用列表推导对初始列表中的值求和
问题描述
我写了这段代码:
rand_map, lst = [2, 2, 6, 6, 8, 11, 4], []
for i in range(len(rand_map)):
num = rand_map[i]
lst.append(num)
for j in range(i+1, len(rand_map)):
assembly = num + rand_map[j]
num += rand_map[j]
lst.append(assembly)
print(sorted(lst))
这给出了这个输出:
[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]
我一直在尝试使用列表推导重写此代码,但我不知道如何。我尝试了多种方法(标准和 itertools),但我就是做错了。我将非常感谢您的帮助!
解决方案
我想出了几个解决这个问题的方法:
方法 1 - 香草列表理解
在这种方法中,我们迭代两个变量,i
并j
计算sum
这两个索引之间的元素。
代码:
>>> rand_map = [2, 2, 6, 6, 8, 11, 4]
>>> sorted([sum(rand_map[i:i+j+1]) for i in range(len(rand_map)) for j in range(len(rand_map)-i)])
[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]
方法 2 - Itertools
In this approach, we use the itertools recipe from here to iterate n-wise through the rand_map
list, and calculate the sums accordingly. This works in approximately the same way as the first approach, but is a bit tider.
Code:
from itertools import islice
def n_wise(iterable, n):
return zip(*(islice(iterable, i, None) for i in range(n)))
print(sorted([sum(x) for n in range(len(rand_map)) for x in n_wise(rand_map, n+1)]))
Output:
[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]
推荐阅读
- haskell - Haskell - 左箭头与嵌套 case 语句
- flutter - Flutter 自定义裁剪器
- javascript - 将数据库值与用户输入相乘
- r - 无法让 rscript 在 rstudio 而不是 web 中打开
- python - 如何联合两个 3d 矩阵以产生相同形状的 2d 矩阵的 3d 矩阵?
- azure - 通过 Azure DevOps 管道部署的 Azure 函数未执行
- javascript - 如何删除别人的消息?不和谐.JS
- python - 将PNG图像从文件夹转换为JPG - Python
- java - 无法在项目上执行目标 org.codehaus.mojo:apt-maven-plugin:1.0-alpha-5:process (default): Apt failed
- mysql - Mysql Sequelize:按年龄最大的选择行分组