本篇文章给大家带来了关于python的相关知识,其中主要介绍了关于元组的相关问题,包括了元组的创建、访问、修改、删除和内置方法等,希望对大家有帮助。
推荐学习:python教程
引言——在Python中,通过数据结构来保存项目中重要的数据信息。Python语言内置了多种数据结构,例如列表,元组,字典和集合等。本堂课我们来讲一讲Python中举足轻重的一大数据结构——元组。
在Python中,我们可以将元组看作一种特殊的列表。它与列表唯一的不同在于:元组内的数据元素不能发生改变【这个不变——不但不能改变其中的数据项,而且也不能添加和删除数据项!】。当我们需要创建一组不可改变的数据时,通常是将这些数据放进元组中~
1.元组的 创建 && 访问
(1)元组的创建:
tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)
# 而且——是可以创建空元组哦!
tuple3 = ()
# 小注意——如果你创建的元组只包含一个元素时,也不要忘记在元素后面加上逗号。让其识别为一个元组:
tuple4 = (22, )
登录后复制
(2)访问:
tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)
# 显示元组中索引为1的元素的值
print("tuple1[1]:", tuple1[0])
# 显示元组中索引从1到3的元素的值
print("tuple2[1:3]:", tuple2[1:3])
登录后复制
2.元组的 修改 && 删除
(1)元组的修改:
tuple1 = ('xiaoming', 'xiaohong', 18, 21)
tuple2 = (1, 2, 3, 4, 5)
tuple_new = tuple1 + tuple2
print(tuple_new)
登录后复制
(1)元组的删除:
tuple1 = ('xiaoming', 'xiaohong', 18, 21)
print(tuple1) # 正常打印tuple1
del tuple1
print(tuple1) # 因为上面删除了tuple1,所以再打印会报错哦!
登录后复制
3.元组的内置方法
- len(tuple):计算元组元素个数;
- max(tuple):返回元组中元素的最大值;
- min(tuple):返回元组中元素的最小值;
- tuple(seq):将列表转换为元组。
其实更多时候,我们是将元组先转换为列表,操作之后再转换为元组(因为列表具有很多方法~)。
4.将序列分解为单独的变量
(1)
tuple1 = (18, 22)
x, y = tuple1
print(x)
print(y)
tuple2 = ['xiaoming', 33, 19.8, (2012, 1, 11)]
name, age, level, date = tuple2
print(name)
print(date)
登录后复制
records = [
('AAA', 1, 2),
('BBB', 'hello'),
('CCC', 5, 3)
]
def do_foo(x, y):
print('AAA', x, y)
def do_bar(s):
print('BBB', s)
for tag, *args in records:
if tag == 'AAA':
do_foo(*args)
elif tag == 'BBB':
do_bar(*args)
line = 'guan:ijing234://wef:678d:guan'
uname, *fields, homedir, sh = line.split(':')
print(uname)
print(*fields)
print(homedir)
print(sh)
登录后复制
(2)
使用内置的deque实现:
from _collections import deque
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
print(q)
q.append(4)
print(q)
登录后复制
from _collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open('123.txt') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines: # 包含python的行
print(pline) # print (pline, end='')
# 打印最后检查过的N行文本
print(line) # print (pline, end='')
登录后复制
123.txt:
pythonpythonpythonpythonpythonpythonpython
python
python
登录后复制
5.实现优先级队列
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
q = PriorityQueue()
q.push(Item('AAA'), 1)
q.push(Item('BBB'), 4)
q.push(Item('CCC'), 5)
q.push(Item('DDD'), 1)
print(q.pop())
print(q.pop())
print(q.pop())
登录后复制
在上述代码中,利用heapq模块实现了一个简单的优先级队列,第一次执行pop()操作时返回的元素具有最高的优先级。
拥有相同优先级的两个元素(foo和grok)返回的顺序,同插入到队列时的顺序相同。
函数heapq.heappush()和heapq.heappop()分别实现了列表_queue中元素的插入和移除操作,并且保证列表中的第一个元素的优先级最低。
函数heappop()总是返回“最小”的元素,并且因为push和pop操作的复杂度都是O(log2N),其中N代表堆中元素的数量,因此就算N的值很大,这些操作的效率也非常高。
上述代码中的队列以元组 (-priority, index, item)的形式组成,priority取负值是为了让队列能够按元素的优先级从高到底排列。这和正常的堆排列顺序相反,一般情况下,堆是按从小到大的顺序进行排序的。变量index的作用是将具有相同优先级的元素以适当的顺序排列,通过维护一个不断递增的索引,元素将以它们加入队列时的顺序排列。但是当index在对具有相同优先级的元素间进行比较操作,同样扮演一个重要的角色。
在Python中,如果以元组(priority, item)的形式存储元素,只要它们的优先级不同,它们就可以进行比较。但是如果两个元组的优先级相同,在进行比较操作时会失败。这时可以考虑引入一个额外的索引值,以(priority, index, item)的方式建立元组,因为没有哪两个元组会有相同的index值,所以这样就可以完全避免上述问题。一旦比较操作的结果可以确定,Python就不会再去比较剩下的元组元素了。
如下——演示了实现一个简单的优先级队列的过程:
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
# ①
a = Item('AAA')
b = Item('BBB')
#a < b 错误
a = (1, Item('AAA'))
b = (5, Item('BBB'))
print(a < b)
c = (1, Item('CCC'))
#② a < c 错误
# ③
a = (1, 0, Item('AAA'))
b = (5, 1, Item('BBB'))
c = (1, 2, Item('CCC'))
print(a < b)
# ④
print(a < c)
登录后复制
在上述代码中,因为在1-2中没有添加所以,所以当两个元组的优先级相同时会出错;而在3-4中添加了索引,这样就不会出错了!
推荐学习:python学习教程
以上就是实例详解Python元组的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是暴躁草莓最近收集整理的关于实例详解Python元组的全部内容,更多相关实例详解Python元组内容请搜索靠谱客的其他文章。
发表评论 取消回复