Python元组剖析

JSON 2024-04-03 16:04:48 248

什么是元组

元组是一个容器,它在括号之间保存一系列逗号分隔的值(项目或元素),例如 (x, y) 坐标。元组类似于列表,但它们是不可变的(即一旦创建就无法更改其内容)并且可以保存混合数据类型。元组在 Python 中扮演着一种“结构”的角色——一种传递一些逻辑的、固定大小的值包的便捷方法。

元组:命令

元组是一个不可变且可哈希的列表。

<tuple> = ()
<tuple> = (<el>, )
<tuple> = (<el_1>, <el_2> [, ...])

命名元组

Tuple 的子类具有命名元素。

>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
>>> p._fields  # Or: Point._fields
('x', 'y')

创建一个元组?

要创建元组,只需列出括号内的值并用逗号分隔。 “空”元组只是一对空括号

>>> #create an empty tuple
>>> tuplex = ()
>>> print (tuplex)
()
>>> #create a tuple with different data types
>>> tuplex = ('tuple', False, 3.2, 1)
>>> print (tuplex)
('tuple', False, 3.2, 1)
>>> #create a tuple with numbers, notation without parenthesis
>>> tuplex = 4, 7, 3, 8, 1 
>>> print (tuplex)
(4, 7, 3, 8, 1)
>>> #create a tuple of one item, notation without parenthesis
>>> tuplex = 4, 
>>> print (tuplex)
(4,)
>>> #create an empty tuple with tuple() function built-in Python
>>> tuplex = tuple()
>>> print (tuplex)
()
>>> #create a tuple from a iterable object
>>> tuplex = tuple([True, False]) 
>>> print (tuplex)
(True, False)
>>>

如何在Python中获取元组的一项?

>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e") 
>>> print(tuplex)
('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
>>> #get item (4th element)of the tuple by index
>>> item = tuplex[3]
>>> print(item)
e
>>> #get item (4th element from last)by index negative
>>> item1 = tuplex[-4]
>>> print(item1)
u
>>>

如何知道Python中的元组中是否存在某个元素?

>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
>>> #use in statement
>>> print("r" in tuplex)
True
>>> print(5 in tuplex)
False
>>>

列表到元组

>>> #create list
>>> listx = [5, 10, 7, 4, 15, 3]
>>> print(listx)
[5, 10, 7, 4, 15, 3]
>>> #use the tuple() function built-in Python, passing as parameter the list
>>> tuplex = tuple(listx)
>>> print(tuplex)
(5, 10, 7, 4, 15, 3)
>>>

将元组解包为多个变量

>>> #create a tuple
>>> tuplex = 4, 8, 3 
>>> print(tuplex)
(4, 8, 3)
>>> n1, n2, n3 = tuplex
>>> #unpack a tuple in variables
>>> print(n1 + n2 + n3) 
15
>>> #the number of variables must be equal to the number of items of the tuple
>>> n1, n2, n3, n4 = tuplex 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>>

在Python元组中添加项目

>>> #create a tuple
>>> tuplex = (4, 6, 2, 8, 3, 1) 
>>> print(tuplex)
(4, 6, 2, 8, 3, 1)
>>> #tuples are immutable, so you can not add new elements
>>> #using merge of tuples with the + operator you can add an element and it will create a new tuple
>>> tuplex = tuplex + (9,)
>>> print(tuplex)
(4, 6, 2, 8, 3, 1, 9)
>>> #adding items in a specific index
>>> tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
>>> print(tuplex)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
>>> #converting the tuple to list
>>> listx = list(tuplex) 
>>> #use different ways to add items in list
>>> listx.append(30)
>>> tuplex = tuple(listx)
>>> print(tuplex)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)
>>>

克隆一个元组

>>> from copy import deepcopy
>>> #create a tuple
>>> tuplex = ("HELLO", 5, [], True) 
>>> print(tuplex)
('HELLO', 5, [], True)
>>> #make a copy of a tuple using deepcopy() function
>>> tuplex_clone = deepcopy(tuplex)
>>> tuplex_clone[2].append(50)
>>> print(tuplex_clone)
('HELLO', 5, [50], True)
>>> print(tuplex)
('HELLO', 5, [], True)
>>>

在Python中如何知道一个项目重复的次数

>>> #create a tuple
>>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 
>>> print(tuplex)
(2, 4, 5, 6, 2, 3, 4, 4, 7)
>>> #return the number of times it appears in the tuple.
>>> count = tuplex.count(4)
>>> print(count)
3
>>> count = tuplex.count(7)
>>> print(count)
1
>>> count = tuplex.count(5)
>>> print (count)
1
>>>

从元组中删除一个项目

>>> #create a tuple
>>> tuplex = "w", 3, "d", "r", "e", "s", "l" 
>>> print(tuplex)
('w', 3, 'd', 'r', 'e', 's', 'l')
>>> #tuples are immutable, so you can not remove elements
>>> #using merge of tuples with the + operator you can remove an item and it will create a new tuple
>>> tuplex = tuplex[:2] + tuplex[3:]
>>> print(tuplex)
('w', 3, 'r', 'e', 's', 'l')
>>> #converting the tuple to list
>>> listx = list(tuplex) 
>>> #use different ways to remove an item of the list
>>> listx.remove("l") 
>>> #converting the tuple to list
>>> tuplex = tuple(listx) 
>>> print(tuplex)
('w', 3, 'r', 'e', 's')
>>>

对元组进行切片

>>> #create a tuple
>>> tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1) 
>>> #used tuple[start:stop] the start index is inclusive and the stop index
>>> _slice = tuplex[3:5] 
#is exclusive.
>>> print(_slice)
(5, 4)
>>> #if the start index isn't defined, is taken from the beg inning of the tuple.
>>> _slice = tuplex[:6]
>>> print(_slice)
(2, 4, 3, 5, 4, 6)
>>> #if the end index isn't defined, is taken until the end of the tuple
>>> _slice = tuplex[5:] 
>>> print(_slice)
(6, 7, 8, 6, 1)
>>> #if neither is defined, returns the full tuple
>>> _slice = tuplex[:]
>>> print(_slice)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
>>> #The indexes can be defined with negative values
>>> _slice = tuplex[-8:-4] 
>>> print(_slice)
(3, 5, 4, 6)
>>>

查找元组中某一项的索引

>>> #create a tuple
>>> tuplex = tuple("index tuple") 
>>> print(tuplex)
('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')
>>> #get index of the first item whose value is passed as parameter
>>> index = tuplex.index("p") 
>>> print(index)
8
>>> #define the index from which you want to search
>>> index = tuplex.index("p", 5) 
>>> print(index)
8
>>> #define the segment of the tuple to be searched
>>> index = tuplex.index("e", 3, 6) 
>>> print(index)
3
>>> #if item not exists in the tuple return ValueError Exception
>>> index = tuplex.index("y")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>>

元组的大小

>>> tuplex = tuple("w3resource")	#create a tuple
>>> print(tuplex)
('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
>>> #use the len() function to known the length of tuple.
>>> print(len(tuplex))
10
>>>

如何在 Python 元组中使用运算符 + 和 *?

>>> #create a tuple
>>> tuplex = 5, #create a tuple
>>> #The * operator allow repeat the items in the tuple
>>> print(tuplex * 6) 
(5, 5, 5, 5, 5, 5)
>>> #create a tuple with repeated items.
>>> tuplex = (5, 10, 15) * 4 
>>> print(tuplex)
(5, 10, 15, 5, 10, 15, 5, 10, 15, 5, 10, 15)
>>> #create three tuples
>>> tuplex1 = (3, 6, 9, 12, 15) 
>>> tuplex2 = ("w", 3, "r", "s", "o", "u", "r", "c", "e")
>>> tuplex3 = (True, False)
>>> #The + operator allow create a tuple joining two or more tuples
>>> tuplex = tuplex1 + tuplex2 + tuplex3
>>> print(tuplex)
(3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False)
>>>

使用步骤参数的元组切片

>>> #create a tuple
>>> tuplex = tuple("HELLO WORLD") 
>>> print(tuplex)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
>>> #step specify an increment between the elements to cut of the tuple.
>>> _slice = tuplex[2:9:2]	#tuple[start:stop:step]
>>> print(_slice)
('L', 'O', 'W', 'R')
>>> #returns a tuple with a jump every 3 items.
>>> _slice = tuplex[::4] 
>>> print(_slice)
('H', 'O', 'R')
>>> #when step is negative the jump is made back
>>> _slice = tuplex[9:2:-4] 
>>> print(_slice)
('L', ' ')
>>> #when step is negative the jump is made back
>>> _slice = tuplex[9:2:-3]	 
>>> print(_slice)
('L', 'W', 'L')
>>>

修改元组的项目

>>> #create a tuple
>>> tuplex = ("w", 3, "r", [], False)
>>> print(tuplex)
('w', 3, 'r', [], False)
>>> #tuples are immutable, so you can not modify items which are also immutable, as str, boolean, numbers etc.
>>> tuplex[3].append(200)
>>> print(tuplex)
('w', 3, 'r', [200], False)
>>>

版权所属:SO JSON在线解析

原文地址:https://www.sojson.com/blog/518.html

转载时必须以链接形式注明原始出处及本声明。

本文主题:

如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。

关于作者
一个低调而闷骚的男人。
相关文章
python编码的意义
Java获取浏览器请求头(User-Agent),分浏览器信息,系统信息的几种办法。
Redis 单线程模型分
Java 完美解.plist & 生成plist ,Android 解.plist
json 解与生成工具类 ,JSON操作讲解(附件)
如何解JSON数据(详细解答)
阿里云DNS 解讲解,SEO配置搜索引擎线路解
SEO实战分-排名最近突然掉光了问题排查,几个大站关键词下降SEO问题分
QUIC / HTTP3 协议详细分讲解
JSOUP 教程,JSOUP爬虫教程,JSOUP超时分与处理
最新文章
JavaScript对象详细剖析 0
Python print() 函数 88
PHP if/else/elseif 语句 114
HTML5 Canvas弧线教程 103
Java赋值运算符 118
XML内部实体和外部实体 217
Java面向对象编程概念 177
PHP回显语句 128
Linux—文件树 157
C语言while循环和do while循环 155
最热文章
最新MyEclipse8.5注册码,有效期到2020年 (已经更新) 683032
苹果电脑Mac怎么恢复出厂系统?苹果系统怎么重装系统? 674756
免费天气API,全国天气 JSON API接口,可以获取五天的天气预报 603346
免费天气API,天气JSON API,不限次数获取十五天的天气预报 582466
Jackson 时间格式化,时间注解 @JsonFormat 用法、时差问题说明 553196
我为什么要选择RabbitMQ ,RabbitMQ简介,各种MQ选型对比 509506
Elasticsearch教程(四) elasticsearch head 插件安装和使用 480123
Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据... ... 265238
Java 信任所有SSL证书,HTTPS请求抛错,忽略证书请求完美解决 244332
Elasticsearch教程(一),全程直播(小白级别) 225702
支付扫码

所有赞助/开支都讲公开明细,用于网站维护:赞助名单查看

查看我的收藏

正在加载... ...