【问题标题】:Create a nested list within a list from given index interval [duplicate]在给定索引间隔的列表中创建嵌套列表[重复]
【发布时间】:2021-03-11 10:26:58
【问题描述】:
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

【问题讨论】:

  • 我不明白您希望这段代码如何解决问题。特别是:仔细想想你.appendlist1是什么,以及为什么;并仔细考虑当i 超出if 条件的范围时会发生什么;并仔细考虑如何知道您何时完成了该过程。
  • 您提供的代码似乎不完整。它似乎收集了应该在新 sub_list 中的元素,但仅此而已。您是否真的尝试过这段代码。请更具体地说明您需要什么帮助。
  • karl knechtel 我是 python 新手,我还在学习,所以请放轻松......谢谢
  • Jolbas 我试过但没用,我还在学习这就是我寻求帮助的原因

标签: python python-3.x list


【解决方案1】:
>>> def nest_elements(list1, start_index, stop_index):
...     list1[start_index:stop_index+1] = [list1[start_index:stop_index+1]]
...     return list1
... 
>>> print(nest_elements([1,2,3,4,5,6],0,4))
[[1, 2, 3, 4, 5], 6]

【讨论】:

    【解决方案2】:

    您可以在此处使用slice assignment*

    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 文档中找不到 Slice Assignment

    【讨论】:

    • 这个答案目前不会复制列表(虽然它很容易添加并且是一种比我更清洁的解决方案)
    • @questionerofdy 啊,真的,slice assignment 已就地。但是我们可以添加out = deepcopy(vals) 以避免变异x。编辑了答案。
    • 也许只是return [*vals[:start], vals[start:end+1], *vals[end+1:]]
    猜你喜欢
    • 2020-05-08
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多