Python刷题系列(7)_元组tuple

简介: Python的元组与列表类似,不同之处在于元组的元素不能修改【1】元组使用小括号,列表使用方括号【2】元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可【3】元组(tuple): 不可变数据类型【4】元组内可以存储任意数据类型【5】如果只创建一个元素的元组,那么这个元素后面必须要加逗号才行

Python Tuple



1、创建空元组


Python的元组与列表类似,不同之处在于元组的元素不能修改

【1】元组使用小括号,列表使用方括号

【2】元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可

【3】元组(tuple): 不可变数据类型

【4】元组内可以存储任意数据类型

【5】如果只创建一个元素的元组,那么这个元素后面必须要加逗号才行


编写一个 Python 程序来创建元组。

#Create an empty tuple 
x = ()
print(x)
#Create an empty tuple with tuple() function built-in Python
tuplex = tuple()
print(tuplex)
print(type(tuplex))
'''
()
()
<class 'tuple'>
'''


2、使用不同的数据类型创建元组


编写一个 Python 程序来创建具有不同数据类型的元组。

#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
'''
('tuple', False, 3.2, 1)
'''


3、创建只有一个元素的元组


#Create a tuple with different data types
tuplex = (1) # 后面不加逗号,则不是元组
print(tuplex)
tuplex = (1,)
print(tuplex)
'''
1
(1,)
'''


4、在元组中添加项


【1】元组是不可变的,因此不能在元组当中添加新元素
【2】可以使用+来添加新元素,但是这样会新建一个元组

tuplex = (4, 6, 2, 8, 3, 1) 
print(tuplex)
#元组是不可变的,因此不能在元组当中添加新元素
#可以使用+来添加新元素,但是这样会新建一个元组
tuplex = tuplex + (9,)
print(tuplex)
'''
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
'''
#在特殊位置插入元素
print(tuplex)
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
'''
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
'''
#将元组变成列表
listx = list(tuplex) 
print(listx)
#在列表里面添加元素
listx.append(31)
#将列表转换为元组
tuplex = tuple(listx)
print(tuplex)
'''
[4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3]
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 31)
'''


5、元组转换为字符串


编写一个 Python 程序以将元组转换为字符串

tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's')
str =  ''.join(tup)
print(str)

026ba37510c04e66b913c426884add21.png

【1】join函数

语法: ‘se’.join(seq)


参数说明

【1】se:分隔符,可以为空

【2】seq:要连接的元素序列、字符串、元组、字典

上面的语法即:以se作为分隔符,将seq所有的元素合并成一个新的字符串

【3】返回值:返回一个以分隔符sep连接各个元素后生成的字符串


6、解压缩几个变量中的元组


编写一个Python程序来解压缩几个变量中的元组。

#create a tuple
tuplex = 4, 8, 3 
print(tuplex)
n1, n2, n3 = tuplex 
#表示将元组里面的每个元素分别赋值给n1,n2,n3
#但是如果变量与元组里面的元素个数不对应的话,会报错
print(n1)
print(n2)
print(n3)
print(n1 + n2 + n3) 
'''
(4, 8, 3)
4
8
3
15
'''


【1】n1, n2, n3 = tuplex

表示将元组里面的每个元素分别赋值给n1,n2,n3
但是如果变量与元组里面的元素个数不对应的话,会报错

tuplex = 4, 8, 3 
print(tuplex)
n1, n2, = tuplex
print(n1)
print(n2)
'''
(4, 8, 3)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_58052/1820726987.py in <module>
      1 tuplex = 4, 8, 3
      2 print(tuplex)
----> 3 n1, n2, = tuplex
      4 print(n1)
      5 print(n2)
ValueError: too many values to unpack (expected 2)
'''


7、获取元组的项


编写一个Python程序,从元组的最后一个元素中获取第4个元素和第4个元素。

tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print(tuplex)
#去从头开始数第4个元素:
item = tuplex[3]
print(item)
#去从结尾开始数第4个元素
item1 = tuplex[-4]
print(item1)
'''
('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
e
u
'''

ba618e6c5fbe4a9fa49e34fc356c58a4.png


8、元组重复项的计数


编写一个Python程序来查找元组的重复项。

tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4) # 这里的4是int类型的,表示计算4出现的次数
print(count)
'''
(2, 4, 5, 6, 2, 3, 4, 4, 7)
3
'''

ed6224fe19f54c08ab86977536db90f0.png

2】count函数

Python count()方法

描述

Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。


count()方法语法:

str.count(sub, start=0,end=len(string))

参数

  • sub – 搜索的子字符串
  • start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
  • end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值:该方法返回子字符串在字符串中出现的次数。


9、检查元组中是否存在元素


tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print("r" in tuplex)
print(5 in tuplex)
'''
True
False
'''

2083cec1a1ae43b5b47ca228c9d57597.png


10、将列表转换为元组


#Convert list to tuple
listx = [5, 10, 7, 4, 15, 3]
print(listx)
tuplex = tuple(listx) #将列表转换成元组
print(tuplex)
'''
[5, 10, 7, 4, 15, 3]
(5, 10, 7, 4, 15, 3)
'''

043aba70242b4228b019a136a4588ce3.png



11、从元组中删除项


编写一个 Python 程序以从元组中删除项。

由于元组本身是不可变的,因此不能直接删除元组当中的元素:

可以使用两个方法对元组当中的元素进行删除:

1、通过切片方式构造新的元组

#create a tuple
tuplex1 = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex1)
tuplex1= tuplex1[:2] + tuplex1[3:]
print(tuplex1)
'''
('w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e')
('w', 3, 's', 'o', 'u', 'r', 'c', 'e')
'''

2、将元组转换成列表,对列表中的元素进行删除之后,再转换成元组

t1= "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(t1)
t=list(t1) 
t.remove("c") 
tuplex = tuple(t)
print(tuplex)
'''
('w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e')
('w', 3, 'r', 's', 'o', 'u', 'r', 'e')
'''


12、对元组进行切片


编写一个 Python 程序来对元组进行切片。

#创建一个元组
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 another 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
#tuple[start:stop:step]
_slice = tuplex[2:9:2]
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', ' ')


13、查找元组项的索引


编写一个 Python 程序来查找元组项的索引。

#create a tuple
tuplex = tuple("index tuple")
print(tuplex)
#('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')    
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")


15、从元组列表中删除空元组


L = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
L = [t for t in L if t ]# 如果是空元组,则返回False
print(L)


90b46315fdc94e0db2cd4c78d66b0dcc.png3f609d69598d47bcad75b285d666ae8b.png



16、将给定的字符串列表转换为元组


def string_list_to_tuple(str1):
    result = tuple(x for x in str1 if not x.isspace()) 
    # 如果x不是空格就加到result元素当中
    return result
str1 = "python 3.0"
print("Original string:")
print(str1)
print(type(str1))
print("\nConvert the said string to a tuple:") 
print(string_list_to_tuple(str1))
print(type(string_list_to_tuple(str1)))

a178dcf1571348c8b21754446eea1107.png


【3】isspace函数

用途:isspace用于判断一个字符串中,是否只包含空格,如果是返回True否则返回False

语法:isspace()

用法:xxx.isspace() 。其中,xxx代表的是一个完整的字符串。


17、计算给定元组的元素总和


编写一个 Python 程序来计算给定元组的元素总和。

原始列表:

(1, 2, 3, 4)

(3, 5, 2, 1)

(2, 2, 3, 1)

所述元组的元素总和:

(6, 9, 8, 6)

x = (1,2,3,4)
y = (3,5,2,1)
z = (2,2,3,1)
print("Original lists:")
print(x)
print(y)
print(z)
print("\nElement-wise sum of the said tuples:")
result = tuple(map(sum, zip(x, y, z)))
print(result)


【4】zip函数

直接实践看用法:

45f3792adb68473db5c11a0c0d553826.png


对于我们的两个list,a和b,list(zip(a, b))生成了一个列表。在这个列表中,每个元素是一个tuple;对于第i个元组,它其中的内容是(a[i-1], b[i-1])。这样的操作,与压缩软件的“压缩”十分接近。如果我们继续在zip()中加入更多的参数,比如zip(a, b, c, d),那么在将它转换成list之后,结果当然就是[(a[0], b[0], c[0], d[0]), (a[1], b[1], c[1], d[1]), …, (a[n-1], b[n-1], c[n-1], d[n-1])]。


事实上,在 Python 3 中,为了节省空间,zip()返回的是一个tuple的迭代器,这也是我们为什么要调用list()将它强制转换成list的原因。不过,Python 2中,它直接返回的就是一个列表了。


18、查找元组的长度



e30e0176392341318aef424e4d328a6d.png

#create a tuple
tuplex = tuple("w3resource")
print(tuplex)
#use the len() function to known the length of tuple
print(len(tuplex))

f344a91b553043828e043b672ee0d35b.png


19、将元组列表转换为字典


344cd02883384e58bc3bf66a315eb09e.png

#create a list
l = [("x", 1), ("x", 2), ("x", 3), ("y", 1), ("y", 2), ("z", 1)]
d = {}
for a, b in l:
    d.setdefault(a, []).append(b)
print (d)

【5】setdefault函数

字典中有一个方法, 如果对于字典中已经有这个key , 直接 return 这个 key 对对应的值,

如果没有 key,会加入这个key。


setdefault(key[, default]) 可以指定一个默认值, 如果没有指定, 则认为是None 返回, 如果指定了default 则直接返回default值


如果有这个key,直接返回字典中对应的key 的值 ,即使设置了default ,也不会返回default, 而是返回 key 对应的value值。

#定义一个空字典
dict = {}
print(dict.setdefault('name','Bill'))
#向字典中添加一个名为name的key,默认值是Bill,输出结果:Bill
print(dict)
#输出结果:{'name': 'Bill'}
print(dict.setdefault('name','Mike'))
#并没有改变name的值,输出结果:Bill
print(dict)
#输出结果:{'name': 'Bill'}
#向字典中添加一个名为age的key,默认值是None,输出结果:None
print(dict.setdefault('age'))
print(dict)
#输出结果:{'name': 'Bill', 'age': None}

image.png


20、将给定的正整数元组转换为整数


编写一个 Python 程序,将给定的正整数元组转换为整数。

原始元组:

(1, 2, 3)

将所述正整数元组转换为整数:

123

原始元组:

(10, 20, 40, 5, 70)

将所述正整数元组转换为整数:

102040570

def tuple_to_int(nums):
    result = int(''.join(map(str,nums)))
    return result
nums = (1,2,3)
print("Original tuple: ") 
print(nums)
print("Convert the said tuple of positive integers into an integer:")
print(tuple_to_int(nums))

892c98bf02d64b7e8cc2227f6c522098.png


相关文章
|
2月前
|
索引 Python 存储
Python 04 之变量【列表,元组,集合,字典,字符串】
Python 04 之变量【列表,元组,集合,字典,字符串】
55 0
Python 04 之变量【列表,元组,集合,字典,字符串】
|
1天前
|
Python
【Python 基础】列表(list)和元组(tuple)有什么区别?
【5月更文挑战第6天】【Python 基础】列表(list)和元组(tuple)有什么区别?
|
10天前
|
存储 索引 Python
【Python21天学习挑战赛】-列表 & 元组 & range
【Python21天学习挑战赛】-列表 & 元组 & range
|
14天前
|
机器学习/深度学习 存储 数据挖掘
Python从入门到精通——学习基础语法和数据类型 1.2.1变量、整数、浮点数、字符串、布尔值、列表、元组、字典和集合。
Python从入门到精通——学习基础语法和数据类型 1.2.1变量、整数、浮点数、字符串、布尔值、列表、元组、字典和集合。
|
22天前
|
容器
06-python数据容器-tuple(元组)
06-python数据容器-tuple(元组)
|
23天前
|
存储 索引 Python
python学习7-元组
python学习7-元组
|
26天前
|
存储 安全 索引
「Python系列」Python元组
Python中的元组(Tuple)是一种不可变的有序序列类型,它允许你存储多个不同类型的元素,并且这些元素在元组中是按照特定的顺序排列的。一旦一个元组被创建,你就不能修改它(即不能添加、删除或更改元组中的元素),这使得元组成为一种非常安全的数据结构,因为一旦它们被创建,就不
23 1
|
28天前
|
索引 Python
python元组内置方法知识
Python元组方法简介:`count()`统计元素出现次数,如`t.count(2)`返回3;`index()`获取元素首次出现的索引,如`t.index(3)`返回2;`insert(index, element)`在指定位置插入元素,如`t.insert(1, &#39;a&#39;)`;`remove(element)`删除元素,如`t.remove(2)`返回 `(1, 3)`;`pop()`删除并返回最后一个元素,如`t.pop()`返回3;`reverse()`反转元组元素,如`t.reverse()`后`t`变为`(3, 2, 1)`。
18 5
|
1月前
|
存储 Java 程序员
【Python】6. 基础语法(4) -- 列表+元组+字典篇
【Python】6. 基础语法(4) -- 列表+元组+字典篇
43 1
|
2月前
|
数据库 索引 Python
Python中collections模块的namedtuple具名元组:原理、应用与优势
在Python的`collections`模块中,`namedtuple`是一个用于创建具有名称属性的元组的工厂函数。它提供了一种更直观、更易于理解的方式来组织和访问数据。通过`namedtuple`,我们可以为元组的每个位置指定一个名字,从而使元组更加有意义和易于操作。本文将深入解析`namedtuple`的原理、使用方法以及它在实际应用中的优势。