绿色应用市场
当前位置:首页 > 学习教程 > 正文

Python基础Lists和tuple实例详解

发布时间:2022-08-26 10:17:51来源:周小白软件园编辑:本站整理

Lists

列表可以包含不同类型的元素,甚至是Lists,但是通常是同一个类型的。

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] print(squares) 

索引和切片

列表支持使用下标索引元素,支持切片.

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] item1 = squares[0] print(item1) item2 = squares[-1] print(item2) squaresShallowCopy = squares[1:3] print(squaresShallowCopy) print(squaresShallowCopy[0]) squaresShallowCopy[1:2]=[] print(squaresShallowCopy) 

输出:

125[4, [1, 2]]4[4]

所有切片操作都会返回一个包含请求元素的新列表,被称为原列表的浅副本。

增删改

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] squares.insert(1,3) print(squares) 

输出:

[1, 3, 4, [1, 2], 'whf', 25]

删除

pop无参数就弹出尾部的,有参数可以指定位置:

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] squares.pop(1) print(squares) 

输出:

[1, [1, 2], 'whf', 25]

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] squares[0]=0 print() 

输出:

[0, 4, [1, 2], 'whf', 25]

连接/拼接

if __name__ == '__main__': squares = [1, 4, [1, 2], "whf", 25] squares+=[66,77] print(squares) squares.append("88") print(squares) print(len(squares)) 

输出:

[1, 4, [1, 2], 'whf', 25, 66, 77][1, 4, [1, 2], 'whf', 25, 66, 77, '88']8

tuple

tuple和list比较类似,但是tuple是不可变的,所以不能增删改。

tuple使用括号括起来,使用逗号分隔元素,如果是简单的元组可以不用:

t = 1, 2, 3 print(t) t = ((1, 2, 3), (4, 5, 6)) print(t) empty = () print(empty) singleton = 'hello', print(singleton) print(len(singleton)) 

输出:

((1, 2, 3), (4, 5, 6))()('hello',)1

解包

t = 1, 2, 3 x, y, z = t print(x, y, z) 

输出:

1 2 3

元素是可变的仍然可变

这个优点像java的final,不能变引用,内容你想变还是可以的:

if __name__ == '__main__': t = ((1, 2, 3), [4, 5, 6]) list=t[1] list[0]=3 print(t) 

输出:

((1, 2, 3), [3, 5, 6])

namedtuple

具名元组,顾名思义就是让普通元组具有名字,方便对元素进行命名和访问:

Student = namedtuple('Student', ['name', 'age', 'city']) s = Student('Xiaoming', '19', 'Beijing') print(s) print(s[1]) print(getattr(s, 'city')) 

输出:

Student(name='Xiaoming', age='19', city='Beijing')19Beijing

以上就是Python之Lists和tuple实例详解的详细内容,更多关于Python Lists tuple的资料请关注云初冀北其它相关文章!

相关推荐

  • Python+pyinstaller%E5%BA%93
    简要pyinstaller模块主要用于python代码打包成exe程序直接使用,这样在其它电脑上即使没有python环
    04月25日 10:22

热门文章

HOT