Home > Backend Development > Python Tutorial > Example analysis of Python tuple creation, assignment and update and delete operations

Example analysis of Python tuple creation, assignment and update and delete operations

黄舟
Release: 2017-07-24 15:24:50
Original
2502 people have browsed it

This article mainly introduces the Python tuple operation method, and combines specific examples to analyze the creation, assignment, update, deletion and other operations of tuples in Python and related precautions. Friends in need can refer to the following

The examples in this article describe Python tuple operations. Share it with everyone for your reference, the details are as follows:


#coding=utf8
'''''
元组是跟列表非常相近的另一种容器类型。
元组是一种不可变类型,一旦创建不可以修改其中元素。
由于这种特性,元组能做一个字典的key。
当处理一组对象时,这个组默认是元组类型。
'''
'''''创建元组并赋值'''
#创建并对一个元组赋值
tuple_1=(1,2,3,"ewang","demo")
#创建一个空的元组
tuple_2=()
#使用tuple创建一个元组并给元组赋值
tuple_3=tuple("hello")
#使用tuple创建一个空的元组
tuple_4=tuple()
'''''访问元组中的值'''
#通过索引使用元组中的值
print tuple_1[0], tuple_1[2], tuple_1[4]
#通过切片使用元组中的值
print tuple_3[0:3],tuple_3[0:],tuple_3[:]
#使用如下操作无法输出整个元组值
#最后一个元素无法输出
print tuple_3[:-1]
'''''
元组是不可变类型,不能更新或者改变元组的元素。
通过现有字符串的片段在构造一个新的字符串的方式来等同于更新元组操作。
'''
#通过索引更新
tuple_1=tuple_1[0],tuple_1[2],tuple_1[4]
print tuple_1
#通过切片更新
tuple_1=tuple_1[0:2]
print tuple_1
'''''
删除一个单独的元组元素是不可能的。
当然,把不需要的元素丢弃后,重新组成一个元组是没有问题的。
要显示地删除一整个元组,只要用del语句减少对象引用计数。
当这个引用计数达到0的时候,该对象就会被析构。
大多数时候,不需要显示的用del删除一个对象,
一出它的作用域它就会被析构。
'''
try:
  del tuple_1
  print tuple_1
except Exception,e:
  print "The tuple_1 not exists ",e
'''''
关于元组的其他操作,与列表的大体相似,再测不做赘述。
相关的源码可以查看关于列表的操作说明。
'''
Copy after login

Running results:

More Python related content Interested readers can check out the special topics on this site: "Python Introduction and Advanced Classic Tutorial", "Python String Operation Skills Summary", "Python List (List) Operation Skills Summary", Python Coding Operation Skills Summary, Python Data Structure and Algorithm Tutorial", "Summary of Python Function Usage Skills" and "Summary of Python File and Directory Operation Skills"

The above is the detailed content of Example analysis of Python tuple creation, assignment and update and delete operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template