首页 > 解决方案 > 在给定索引间隔的列表中创建嵌套列表

问题描述

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

标签: pythonpython-3.xlist

解决方案


您可以在此处使用切片分配*

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 文档中找不到切片分配


推荐阅读