python - 在给定索引间隔的列表中创建嵌套列表
问题描述
def nest_elements(list1, start_index, stop_index):
'''
Create a nested list within list1. Elements in [start_index, stop_index]
will be in the nested list.
Example:
>>> x = [1,2,3,4,5,6]
>>> y = nest_elements(x, 0, 4)
>>> print(y)
>>> [[1, 2, 3, 4, 5], 6]
Parameters:
----------
list1 : (list)
A heterogeneous list.
start_index : (int)
The index of the first element that should be put into a nested list
(inclusive).
stop_index : (int)
The index of the last element that should be put into a nested list
(inclusive).
Returns:
----------
A copy of list1, with the elements from start_index to stop_index in a
sub_list.
'''
for i in range(len(list1)):
if i>= start_index or i<= stop_index:
list1.append(i)
return list1
pass
解决方案
您可以在此处使用切片分配*。
from copy import deepcopy
def nested(vals, start, end):
out = deepcopy(vals)
out[start:end+1] = [out[start:end+1]]
return out
x = [1,2,3,4,5,6]
out = nested(x, 0, 4)
out
# [[1, 2, 3, 4, 5], 6]
* 我附上了 SO 链接,因为我在 python 文档中找不到切片分配
推荐阅读
- jupyter-notebook - 当 Jupyter Hub 中的 Python 文件很大时,无法添加目录扩展
- azure-data-factory - 在 .net 核心中使用 .NET SDK 创建 Azure 数据工厂?
- arrays - Hackerrank 中 numpy 的眼睛和身份功能。为什么测试用例失败了?
- uwp - CalendarDatePicker,TodayDate 在 UWP 中没有突出显示?
- python - 如果该行与DataFrame中的其他行有一定关系,如何删除行?
- node.js - 如何使用 node.js 和 pm2 将 verdaccio 发布到互联网?
- sql - sql中存储过程的嵌套循环不起作用
- c++ - 为什么我在提交leetcode时会报错,但在IDE中使用相同的代码?
- retrofit2 - 带有 Retrofit 2 的 kotlinx 序列化中的构建错误
- python - 我刚刚开始用 Python 制作一个基本的交互式计算器,但不知道为什么它不接受给定的输入