【问题标题】:List Slicing in Python Without Using Built-In Function?不使用内置函数的 Python 列表切片?
【发布时间】:2017-07-22 12:43:15
【问题描述】:

我对编程很陌生,目前在一个涉及列表切片的实践问题上遇到了问题,而没有使用内置函数,所以我的想法是创建自己的切片函数以供用户调用。以下是问题,接下来是我尝试解决的问题。任何帮助表示赞赏。谢谢!

Python 为列表提供了切片功能,但是对于这个问题,您将实现自己的能够生成列表切片的函数(注意:您不能在解决方案中使用切片运算符)。该函数应称为 slice 并按此特定顺序接受以下三个输入:

  1. 将从中创建切片的列表源。您的函数无法修改此列表。
  2. 一个正整数 start,表示您将创建的切片的起始索引。如果此值不在 [0, len(list)-1] 范围内,则您的函数应返回一个空列表。
  3. 一个正整数 end,表示您将创建的切片的结束索引。如果此值不在 [start, len(list)-1] 范围内,您的函数应返回一个空列表。
    如果参数值是可接受的,您的函数将返回一个列表,其中包含从索引开始到索引结束(包括)的源中的项目。这与 Python 切片运算符不同,因为索引末尾的项目也包含在新列表中。

示例:

mylist = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]  
slice(mylist, 0, 9) should be ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] slice(mylist, 3, 4) should be ["D", "E"]  
slice(mylist, 4, 3) should be [ ]  
slice(mylist, 3, 8) should be ["D", "E", "F", "G", "H", "I"]  
slice(mylist, 4, 4) should be ["E" ]

我的代码:

source=int(input("Enter a list: "))  
start=int(input("Enter the starting digit: "))  
end=int(input("Enter the ending digit: "))  
  
def slice(source,start,end):  
        if start is not [0, len(source)-1]:
            print()  
        elif end is not [start, len(source)-1]:  
            print()  
    source.append(0,start)  
    source.append(len(source),end)  
  
slice[]

【问题讨论】:

  • 不错的尝试。你有什么问题?
  • @Mitch 我看不出这次尝试有什么好处。
  • @Mitch 谢谢:p 问题在示例之上。
  • @Ev.Kounis 很有建设性,很友善,谢谢
  • @kleenexbox,如果超出索引会怎样?

标签: python list slice


【解决方案1】:

我自己想出来了,感谢您在不居高临下的情况下提供帮助 @lmiuelvargasf 我真的很感激。

start = int(input(" Enter the starting index of the slice you will create: "))
end = int(input("Enter the ending index of the slice you will create:  "))
def slice(source, start, end):
    myList = []
    for i in range(start, end+1):
        if start in range(0, len(source)) and end in range(start,     len(source)):
        myList.append(source[i])
return myList

myList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] #This is the source
print(slice(myList,start,end))

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2017-06-24
    • 2015-02-19
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多