python - 我需要选择 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 工作但它根本不只是打印列表它是如何没有任何更改
解决方案
生成所有立方体,然后选择小于 100 的立方体。
from itertools import takewhile, count
cubes1to100 = list(takewhile(lambda x: x <= 100, map(lambda x: x**3, count())))
分解它:
count()
产生无限的整数流 0, 1, 2, ....map(lambda x: x**3, count())
产生无限的立方体流 0, 1, 8, 27, 64, 125, ....takewhile(...)
通过仅产生那些map
小于或等于 100 的值来生成小于 100 的有限立方体流。list
,最后,从返回的迭代创建一个列表takewhile
。
迭代器都是惰性的,所以x ** 3
只计算了 6 次,就像x <= 100
.
推荐阅读
- python - logger.disabled 稍后在 python 日志记录模块中检查。理由是什么?
- java - Spring MappingJackson2HttpMessageConverter 没有被触发?
- redirect - Phoenix 框架:在控制器之间传递变更集错误
- java - 如何将 Maven 项目转换为 Spring REST 服务
- angular - 将数据库中保存的日期时间值分配给 Datepicker 值
- perl - Perl PDF::API2 显示纯 ASCII 字母的框
- html - iOS 与 webView 共享 pdf
- php - 如何在我的 Web 服务器上提供目录的绝对路径
- javascript - Pinterest 标签在单页应用程序上多次触发
- java - 没有类型信息的杰克逊多态反序列化