python - Python:如何循环列表并附加到新列表
问题描述
下面的列表a
打印了 0 到 5 之间的所有项目:
[1, 2, 3, 2, 3]
a = [100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98]
def new_list(x):
new = []
for item in range(len(x)):
if x[item] < 5 and x[item] > 0:
new.append(x[item])
return new
print new_list(a)
如何打印项目在 0 到 5(含)之间的子列表,如果项目超出范围,则开始一个新的子列表?
预期输出:
[1],[2,3,5],[2,3]
解决方案
那你应该再列一张清单。
def new_list(x):
new = []
returns = []
for item in x: # <- I modified the for loop
if item < 5 and item > 0:
new.append(item)
elif len(new) > 0: # <- if out of range and new is not empty
returns.append(new)
new = []
if len(new) > 0: # <- last new check
returns.append(new)
return returns
推荐阅读
- go - 如何将钩子添加到 zap 记录器中?
- c++ - 转储 apache thrift 消息以进行调试?
- delphi - 在 delphide 中使用动态字节数组时出现错误
- ios - 用于 Swift 初始化 iZettles 库的 Objective C 等效代码
- wordpress - 如何创建过滤器以显示自定义帖子类型
- avfoundation - AVAssetExportSession 通过 EXC_BAD_INSTRUCTION
- javascript - 捕获错误未通过 nightwatchjs 测试
- octave - 如何正确计算非线性函数并在 Octave 中绘制其图形?
- java - 为什么 Eclipse Ide 和 Tool Suite 不会编译/运行我的类,只是主类或前一个类
- flutter - 如何在 pubspec.yaml 中添加用户定义的变量以进行颤振?