Python基础Lists和tuple怎么应用

发布时间:2022-08-26 10:18:04 作者:iii
来源:亿速云 阅读:105

这篇“Python基础Lists和tuple怎么应用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python基础Lists和tuple怎么应用”文章吧。

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)

输出:

1
25
[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')
19
Beijing

以上就是关于“Python基础Lists和tuple怎么应用”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. python 元组tuple(14)
  2. list和tuple

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python lists tuple

上一篇:Python中的list.sort()方法和函数sorted(list)怎么用

下一篇:怎么用React实现拖拽调整大小的组件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》