Python3列表.pop()与sli

2024-09-28 22:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于:

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

如果我们只考虑l的末态,l.pop(0)和{}之间有什么区别?在

在我看来,l的内容应该是相同的,不管我选择哪个选项,简单的测试似乎都是一样的,但是我有一段代码根据我使用的操作而表现出不同的行为。在

我使用的是Anaconda的Python3.6.7。在

编辑:代码示例:

^{pr2}$

为什么结果不同?在

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


Tags: 代码元素编辑示例内容列表选项anaconda
2条回答

主要区别是一种是按值调用,另一种是引用调用。 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()打印list afret的列表是否不再包含thet元素

l[1:]:slice()构造函数创建一个slice对象,它表示由range(start,stop,step)指定的一组索引,在您的例子中,您得到了一个新的list,其中包含开始对对象进行切片的整数

相关问题 更多 >