基础数据类型-tuple
2024-08-26 16:56:38
Python中,元组tuple与list类似,不同之处在于tuple的元素不能修改,tuple使用(),list使用[],
(1)元组的创建使用(),需要注意的是创建包含一个元素的元组:
tuple_number = ()
tuple_number = (1, ) #创建一个元素的元组,在元素后加逗号
print("type of (1) is:", type((1))) #(1)的类型是整形 type of (1) is: <class 'int'>
(2)元组的索引,切片,检查成员,加,乘
#索引
tuple_number = (1, 2, 3, 4, 5)
print("tuple_number[2]:", tuple_number[2])
#切片
print("tuple_number[1:4]:", tuple_number[1:4])#index = 4的元素不包含
#检查成员
if 6 in tuple_number:
print("6 is in tuple_number")
else:
print("6 is not in tuple_number")
#加
tuple_name = ('John', 'Paul')
print("tuple_number plus tuple_name:", tuple_number + tuple_name)
#乘
print("tuple_number * 2:", tuple_number * 2)
Code
tuple_number[2]: 3
tuple_number[1:4]: (2, 3, 4)
6 is not in tuple_number
tuple_number plus tuple_name: (1, 2, 3, 4, 5, 'John', 'Paul')
tuple_number * 2: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Result
(3)tuple的遍历和list一样: for number in tuple_number:print(number)
(4)与list一样,tuple也有函数:len(),max(),min(),tuple()
(5)由于tuple的元素不允许修改,tuple的内置方法只有count(),index()
#方法
tuple_number = (1, 1, 2, 2, 2, 3, 3, 3, 3)
print("count of 2 in tuple_number:", tuple_number.count(2)) #元素出现的次数
print("index of first 3:", tuple_number.index(3)) #元素第一次出现的位置
Code
count 2 in tuple_number: 3
index of first 3: 5
Result
(6)最后看看tuple类的定义:
class tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
Class Tuple
最新文章
- ArcGIS ElementLayer上放置Windows控件
- 背景:表A数据误操作,被delete了,恢复。
- 2014年QS世界大学排名
- 【PHPsocket编程专题(实战篇③)】构建基于socket的HTTP请求类
- ios开发 数据库版本迁移手动更新迭代和自动更新迭代
- HDU 5501 The Highest Mark 背包dp
- JIRA Cannot Start Due to 'unable to clean the cache directory: /opt/jira/plugins/.osgi-plugins/felix'
- 怎么用visual studio2010编写c++程序|用visual studio2010编写c++程序的步骤
- android studio 环境配置
- cocos2d_x_06_游戏_一个都不能死
- I/O概述和审查操作
- 原生AJAX基础讲解及兼容处理
- 转:【Java并发编程】之十六:深入Java内存模型——happen-before规则及其对DCL的分析(含代码)
- Django Channels 入门指南
- python3 第二十八章 - 内置函数之List相关
- 朱晔和你聊Spring系列S1E10:强大且复杂的Spring Security(含OAuth2三角色+三模式完整例子)
- Post Tuned Hashing,PTH
- 【Acm】算法之美—Jugs
- struct timeval 计时问题
- Spark高级数据分析&#183; 2数据分析