首页 > 解决方案 > 我需要选择 1 到 100 之间的立方体值

问题描述

cubos = [valor**3 for valor in range(1,101)]#creates a list the cubes from 1 to 100
for cubo in cubos:#loop and create the internal values
    if cubo >= 100:#pick the values bigger then 100
        del cubo #delete them
print (cubos)#print the values lower then 100

为什么不工作我希望它使 if 工作但它根本不只是打印列表它是如何没有任何更改

标签: pythonmath

解决方案


生成所有立方体,然后选择小于 100 的立方体。

from itertools import takewhile, count

cubes1to100 = list(takewhile(lambda x: x <= 100, map(lambda x: x**3, count())))

分解它:

  1. count()产生无限的整数流 0, 1, 2, ....
  2. map(lambda x: x**3, count())产生无限的立方体流 0, 1, 8, 27, 64, 125, ....
  3. takewhile(...)通过仅产生那些map小于或等于 100 的值来生成小于 100 的有限立方体流。
  4. list,最后,从返回的迭代创建一个列表takewhile

迭代器都是惰性的,所以x ** 3只计算了 6 次,就像x <= 100.


推荐阅读