Python3 List.md

List, a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
列表,中括号 中一列用 逗号 分隔的值。列表可以包含不同类型的元素,但是通常所有的元素都具有相同的类型。

>>> list = [1, 2, 3, 4, 5];
>>> list
[1, 2, 3, 4, 5]
>>> print(list);
[1, 2, 3, 4, 5]

和字符串(以及其它所有内置的 sequence)一样,列表也可以 索引切片
无论正负索引号,都是从左边开始读取的。只要 slice[x: y]x 的索引位置在 y 的左边,无论正负索引都可以切片得到新的有值的切片。否则,都是得到空值切片([]'')

>>> list = [1, 2, 3, 4, 5];
>>> list[0]
1         'indexing returns the item'
>>> list[-1]
5    
>>> list[ : 3]
[1, 2, 3]         'slicing returns a new list'
>>> list[3: ]
[4, 5]
>>> list[-3: ]    
[3, 4, 5]
>>> list[-5: 2]    '== list[-5: -3]'
[1, 2]
# 注意,无论正负索引都是从左边开始的,所以,想要用负的索引切片全部,应该是 list[-5: ],而不是 list[-1: ]
>>> list[-5: ]
[1, 2, 3, 4, 5]
>>> list[-1: ]
[5]

列表也支持 +* 连接。

>>> list = [1, 2, 3, 4, 5];
>>> list1 = [0] + list + 3*[6];
>>> list1
[0, 1, 2, 3, 4, 5, 6, 6, 6]

Unlike strings, which are immutable, lists are a mutable type. i.e. (id est[id'est] (拉丁)也就是) it is possible to change their content.
不像不可改变的字符串,列表是可以改变的。也就是说,可以改变列表的内容。
列表可以只改变一个索引的值,也可以改变一个切片的值。因此,可以改变一个列表的大小或清空列表。
注意,不能够通过索引删除或增加一个值。因为,列表的值是可以是不同类型的。所以,对一个索引赋值 []' ' 都只是改变值,不是删除这个索引值。要删除列表的某个值只能够通过切片选择一个值 list[i: i+1]
如果想要增加值到列表,也可以通过切片来实现 list[i: n] = [value]。注意,增加的值要用 [] 括起来。

>>> list = [0, 1, 2, 2, 2, 2, 2];
>>> list[3] = 3;    #改变一个索引的值
>>> list
[0, 1, 2, 3, 2, 2, 2]
>>> list[4: ] = [4, 5];    #改变一个切片的值
[0, 1, 2, 3, 4, 5, 2]
>>> list[-3: -1] = [];    #删除某个切片
>>> list
[0, 1, 2, 3, 2]
>>> list[-1] = [];    #对索引只能够赋值,不能够删除某个索引值
>>> list
[0, 1, 2, 3, []]
>>> list[-1: ] = []   #想要删除某个值只能够通过切片选择这个值来删除
>>> list
[0, 1, 2, 3]
>>> list[len(list): ] = [4];    # 在 list[4] 增加值 4。 注意,增加的值一定要加 '[]' ,否则会报错。
>>> list
[0, 1, 2, 3, 4]
>>> list[len(list)] = [4]    # 不能够通过索引来增加或删除值
IndexError: list assignment index out of range
>>> list[len(list): ] = [5, 6, 7]    # 也可以增加多个值,不一定要与切片的大小一致
>>> list
[0, 1, 2, 3, 4, 5, 6, 7]
>>> list[3: 5] = ['a', 'b', 'c'];    # 替换指定的切片值,不一定要与切片的大小一致
>>> list
[0, 1, 2, 'a', 'b', 'c', 5, 6, 7]
>>> list[3: 6] = [3, 4];
>>> list
[0, 1, 2, 3, 4, 5, 6, 7]
>>> list = [];    #清空列表
>>> list
[]    # 清空列表,不是删除列表,列表还是存在的只是值为空了

The built-in function len() also applies to lists.

>>> list = [0, 1, 2, 3];
>>> len(list);
4

It is possible to nest lists.

>>> list = [0, 1, 2];
>>> list1 = ['a', 'b']
>>> list = [list, 0, 'abc', list1];
>>> list
[[0, 1, 2], 0, 'abc', ['a', 'b']]


转载于:https://www.cnblogs.com/lizsCnBlog/p/4960232.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值