【问题标题】:list slicing without using the slice function列表切片而不使用切片函数
【发布时间】:2017-07-27 00:08:53
【问题描述】:

Python 为列表提供了切片功能,但为此 问题,您将实现自己的功能,能够产生 列出切片(注意:你不能在你的 解决方案)。该函数应称为slice 并采用以下内容 按此特定顺序的三个输入:

  1. 一个列表,source,将从中创建切片。您的函数无法修改此列表。
  2. 一个正整数start,表示您将创建的切片的起始索引。如果此值不在[0, len(list)-1] 范围内,您的函数应返回一个空列表。
  3. 一个正整数end,表示您将创建的切片的结束索引。如果此值不在[start, len(list)-1] 范围内,您的函数应返回一个空列表。

如果 参数值是可以接受的,你的函数将返回一个列表 包含来自source 的项目,从索引start 开始并结束 在索引end(包括)。这与 Python 切片不同 运算符,因为索引 end 处的项目也包含在新的 列表。

这是我目前得到的:

    list1 = []
def slice(list1):
    list1 = list(input("enter a list"))
    emptylist = []
    st = int(input("enter start"))

    ed = int(input("enter end"))


    if ed not in range(st,len(list1)-1) or st not in range(0,len(list1)-1):
        print(emptylist)
    else:
        list2 = []

        for i in list1:
            list2.append(list1[i])
            return(list2)

print(slice(list1))

【问题讨论】:

  • 你的家庭作业说明没有提到接受用户输入。或者至少,我相当肯定你的函数应该将这些作为参数
  • @juanpa.arrivillaga 该列表必须从用户那里获取,并且不能被函数操作或更改。 1- 一个列表,源,切片将从中创建。您的函数无法修改此列表。
  • 您的解决方案在我看来还可以。你试过运行它吗?补充一下 juanpa 所说的,该函数不应该要求参数。应该是这样的:def slice(List, start, end):应该这样声明。
  • 再一次,我很确定您的说明暗示该函数应将这些值作为参数
  • 你的切片只接受一个参数

标签: python list slice


【解决方案1】:

我不知道应该如何分隔列表输入,所以我不会将它包含在我的答案中。事实上,我只是假设我们以某种方式从用户那里收到了正确格式的列表,并且只需要调用该列表中的函数。

您的函数将采用 3 个参数,startendlist 本身,因为这些是切片任务的最低要求。

def slice(lst, start, end):

最简单的解决方案是遍历循环并添加start:end 范围内的所有元素。毕竟,您可以使用索引符号。

您首先必须创建一个仅包含适当元素的空列表。我们将此列表称为output 列表。

output = []

然后,我们可以遍历startend 之间的所有整数,因为列表索引是整数。

for i in range(start, end):
    output.append(lst[i])

在函数结束时,您可能希望返回 output 列表,以便最终得到一个实际切片的列表对象。

return output

把它们放在一起:

# some shebangs here
'''
Some docstring here
'''
# some imports here

# receive user input. You need a list and two integers.
# lst = input()
# start = input()
# end = input()

def slice(lst, start, end):
    output = []
    if not(0 <= start < len(lst)):
        return output
    elif not(start <= end < len(lst)):
        return output
    else:
        for i in range(start, end+1):
            output.append(lst[i])
        return output

print(slice(lst, start, end))


为什么您的原始脚本不起作用?

您的代码的问题在最后一行。如果你这样做:

for i in list1:
    list2.append(list1[i])
    return(list2)

首先,i 是被迭代的元素,不是元素的索引。其次,返回终止函数,因此终止循环。结果,脚本不仅会抛出IndexError,而且即使你很幸运,它也会返回一个只有一个元素的列表。你可以这样修改:

for i in list1:
    list2.append(i)
return list2

这会起作用,只是现在我们忽略了startend 参数。 (这就是我选择range() 函数的原因)。如果您想使用 Pythonic 表示法,您将枚举列表,检查索引,并在适当的情况下追加。

for index, element in enumerate(list1):
    if start <= index <= end:
        list2.append(element)
return list2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2020-05-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多