Given a list, start and end index, we have to create a list from specified index of the list in Python.
给定一个列表,开始和结束索引,我们必须根据Python中列表的指定索引创建一个列表。
Example 1:
范例1:
Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end = 4
Logic to create list with start and end indexes:
List1 = list[start: end+1]
Output:
list1: [20, 30, 40, 50]
Example 2:
范例2:
Input:
list : [10, 20, 30, 40, 50, 60]
start = 1
end = 6
Logic to create list with start and end indexes:
list1 = list[start: end+1]
Output:
Invalid end index
Logic:
逻辑:
Take a list, start and end indexes of the list.
取得列表,列表的开始和结束索引。
Check the bounds of start and end index, if start index is less than 0, print the message and quit the program, and if end index is greater than the length-1, print the message and quit the program.
检查开始和结束索引的界限,如果起始索引小于0,则打印该消息并退出该程序,并且如果结束索引大于长度-1时,打印该消息并退出该程序。
To create a list from another list with given start and end indexes, use list[n1:n2] notation, in the program, the indexes are start and end. Thus, the statement to create list is list1 = list[start: end+1].
要使用给定的开始索引和结束索引从另一个列表创建列表,请使用list [n1:n2]表示法,在程序中,索引为start和end 。 因此,创建列表的语句为list1 = list [start:end + 1] 。
Finally, print the lists.
最后,打印列表。
Program:
程序:
# define list
list = [10, 20, 30, 40, 50, 60]
start = 1
end = 4
if ( start < 0):
print "Invalid start index"
quit()
if( end > len(list)-1):
print "Invalid end index"
quit ()
# create another list
list1 = list[start:end+1]
# printth lists
print "list : ", list
print "list1: ", list1
Output
输出量
list : [10, 20, 30, 40, 50, 60]
list1: [20, 30, 40, 50]
Size of the list is 6, and indexes are from 0 to 5, in this example the end index is invalid (which is 6), thus program will print "Invalid end index" and quit.
列表的大小为6,索引从0到5,在此示例中,结束索引无效(为6),因此程序将打印“ Invalid end index”并退出。
Note: Program may give correct output if end index is greater than the length-1 of the list. But, to execute program without any problem, we should validate the start and end index.
注意:如果结束索引大于列表的长度1 ,则程序可能会给出正确的输出。 但是,要执行程序没有任何问题,我们应该验证开始索引和结束索引。
# define list
list = [10, 20, 30, 40, 50, 60]
start = 1
end = 6
if ( start < 0):
print "Invalid start index"
quit()
if( end > len(list)-1):
print "Invalid end index"
quit ()
# create another list
list1 = list[start:end+1]
# printth lists
print "list : ", list
print "list1: ", list1
Output
输出量
Invalid end index
翻译自: https://www.includehelp.com/python/create-a-list-from-the-specified-start-to-end-index-of-another-list.aspx