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