列表操作之定义,切片(取元素)(Python)

学完列表,元组,字典,集合以后,发现他们长的有些像,傻傻分不清,现在回顾下,以代码为例进行分析每一种操作的属性。(英语不佳,错误请忽略)

举栗如下:

names = ["hbb",'tian','bao','cheng'] # define of list 符号为 [] not () or {} # find one element
print(names [0]) # hbb 以零作为开始;对照位置查找元素; # print(names[ ]) # 'list' object is not callable 直接括号无效 # print(names( )) # 'list' object is not callable 不是() # print(names(-1)) # 'list' object is not callable 不是() print(names[-1]) # cheng 是[] #切片,取多个元素 print(names[1:3]) # ['tian', 'bao'] including 1,but not including 3 顾头不顾尾 print(names[1:-1]) # ['tian', 'bao'] including 1,but not inckding -1 顾头不顾尾 print(names[1:]) # ['tian', 'bao', 'cheng'] -1 can be bypass, but including -1 不写-1可以去到尾(这样写可以取到最后一个) print(names[0:3]) # ['hbb', 'tian', 'bao'] print(names [:3]) # ['hbb', 'tian', 'bao'] 0 can 省略 不写0 和 不写-1的情况不同:写不写0,都能取0;但是写不写-1却很不同。 print(names[:]) # ['hbb', 'tian', 'bao', 'cheng'] 0 and -1 all could bypass #print(names[ ]) # 'list' object is not callable [] 里面有点才好使 print(names[0:3:2]) # ['hbb', 'bao'] 步长取样 print(names[::2]) # ['hbb', 'bao'] 0 and -1 all could bypass print(names)

总结:

列表的表示方法为 list = ['a','b',"c"]

根据位置取元素:0为开始,-1也可以作为开始。

可以单个取样:print(list [2])

多个取样:print(list[0:3]), print(list[:3]), print(list[0:-1]), print(list[0:])

全部取样:print(list[:])

步长取样:print(list[0:3:2]), print(list[::2])

原文地址:https://www.cnblogs.com/hanbb/p/7204862.html