gpt4 book ai didi

python - 为什么[:1] and [0] do not generate the same result?

转载 作者:行者123 更新时间:2023-11-30 21:57:47 25 4
gpt4 key购买 nike

为什么方法 1 和方法 2 打印的输出不一样?

>>> names = ["Apple", "Samsung", ]

# Method 1/Print the first item in names
>>> print(names[:1])
['Apple']

# Method 2/Print the first item in names
>>> print(names[0])
Apple

最佳答案

切片语法(方法 1)始终会生成一个新列表,即使新列表只有一项。

索引(方法 2)会在可迭代对象的该位置生成项目。

关于python - 为什么[:1] and [0] do not generate the same result?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com