Python 3 list.pop() vs slice



鉴于:

l = [1,2,3,4,5]

如果我们只考虑l的最终状态,l.pop(0)l = l[1:]有什么区别?

在我看来,无论我选择哪个选项,l的内容都应该相同,简单的测试似乎显示相同,但我有一段代码,根据我使用的操作,它的行为会有所不同。

我使用的是 Anaconda 的 Python 3.6.7。

编辑:代码示例:

forward = range(10)
backward = forward[::-1]
parts = []
f_p = []
b_p = []
for f, b in zip(forward, backward):
    if len(f_p) == 3:
        parts.append((f_p, b_p))
        f_p = f_p[1:] # f_p.pop(0)
        b_p = b_p[1:] # b_p.pop(0)
    f_p.append(f)
    b_p.append(b)
print(parts)

为什么结果不同?

附言我知道pop()返回元素,但我目前只关心列表本身。

主要区别在于一个是按值调用,另一个是按引用调用。pop 会影响原始列表,而切片在您明确使其生效之前不会

def test_pop(ls):
    return ls.pop(0)
def test_slice(ls):
    return ls[1:]
l = [1,2,3,4,5]
print(l) #[1, 2, 3, 4, 5]
test_slice(l)
print(l) #[1, 2, 3, 4, 5] doesn't effect the original list
test_pop(l)
print(l) #[2, 3, 4, 5] effects the original list

如果您只是尝试打印结果,您将看到结果:

l = [1,2,3,4,5]
print (l.pop(0)) # 1: The method returns the removed item
print (l) # [2, 3, 4, 5] # list after removing item
l = [1,2,3,4,5]
print (l[1:]) # [2, 3, 4, 5] # new list with starting integer where the slicing of the object starts

l.pop(0) :pop(( 方法从列表中删除给定索引处的项目。该方法还返回已删除的项目,在您的情况下返回 1,如何查看是否使用 pop(( 打印列表 afret,您的列表不再包含 thet 元素

l[1:] :slice(( 构造函数创建一个 slice 对象,表示由 range(start、stop、step( 指定的索引集,在您的情况下,您获得了具有起始整数的新列表,其中对象的切片开始

最新更新