Python 3 list.pop()与slice

时间:2019-07-11 10:46:43

标签: python python-3.x list-comprehension

鉴于:

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

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

在我看来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)

为什么结果不同?

P.S。我知道pop()返回了元素,但是我目前只关心列表本身。

2 个答案:

答案 0 :(得分:1)

主要区别在于:一个是按值调用,另一个是按引用调用。 弹出效果会影响原始列表,而切片则要等到您明确将其设为

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

答案 1 :(得分:0)

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

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)指定的索引集,在您的情况下,您将获得一个以起始整数开头的新列表,其中该对象的切片开始