python元组与字典
一、元组
1.元组的表达
(1,2,3,4)
('olive',123)
("python",)
创建元组:
a=tuple((1,2,3,))
b=("python",)
2.元组功能属性
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 def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass def __init__(self, seq=()): # known special case of tuple.__init__
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
tuple
3.元组的部分功能属性介绍
元组和列表有很大相似性,但是元组的元素是不可修改的,所以很多列表有的功能元组都没有。
1)count(self, value):
统计元组中包含value元素的数量,返回一个int值。
a=(1,2,3,4,1,2,3,1,2,)
b=a.count(1)
print(a,type(a))
print(b,type(b)) #运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) <class 'tuple'>
3 <class 'int'>
demo
2)index(self, value, start=None, stop=None):
索引,查找元组中value元素第一个出现的位置,start与stop参数是查找起始与结束位置,默认为None,返回int数值,如果查找中不包含这个元素,则返回ValueError: 'f' is not in tuple报错。
a=(1,2,3,4,1,2,3,1,2,)
b=a.index(3)
print(a,len(a))
print(b,type(b)) #运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) 9
2 <class 'int'>
demo
3)__add__(self, *args, **kwargs):
给元组添加一个新的元素,添加的新元素需要以元组的形式添加,生成一个新的元组。
a=(1,2,3,4)
b=a.__add__((5,1)) #括号理给出的必须是元组
print(a,type(a))
print(b,type(b)) #运行结果
(1, 2, 3, 4) <class 'tuple'>
(1, 2, 3, 4, 5, 1) <class 'tuple'>
demo
4)__contains__(self, *args, **kwargs):
判断元组中是否包含某个元素,返回布尔值。
a=(1,2,3,4,1,2,3,1,2,)
b=a.__contains__(2)
c=a.__contains__(5)
print(a)
print(b)
print(c) #运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2)
True
False
demo
二、字典
1.字典的表达
{"name":"olive","age":18}
创建字典:
a={"name":"olive","age":18}
b=dict({"name":"lusi","age":18})
2.字典功能属性
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None
dict
3.字典的部分功能属性介绍
1)clear(self):
清除字典中的所有元素。
a={"name":"olive","age":18}
b=a.clear()
print(a)
print(b)
#运行结果
{}
None
demo
2)copy(self):
复制一份元组,相当于一次浅拷贝。
a={"name": "olive","age":18}
b=a.copy()
print(a,id(a),id("name"))
print(b,id(b),id("name"))
#赋值
c={"name": "lusi","age":18}
d=c
print(c,id("name"))
print(d,id("name"))
#浅拷贝
e={"name": "shy","age":18}
f=copy.copy(e)
print(e,id(e),id("name"))
print(f,id(f),id("name"))
#运行结果
{'name': 'olive', 'age': 18} 2915224 2019840
{'name': 'olive', 'age': 18} 2915304 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'shy', 'age': 18} 5584616 2019840
{'name': 'shy', 'age': 18} 5586056 2019840
demo
3)fromkeys(*args, **kwargs):【fromkeys(seq,value=None)】
创建一个新的字典,以seq为字典的keys(键),value为字典的值,默认为None。适合创建一个一样值的字典。
a={"hunan": "changsha","guangdong":"guangzhou","jiangsu":"nanjing",'hubei':"wuhan"}
b=dict.fromkeys(a,"good")
c=dict.fromkeys(["a","b","c"],"abc")
d=dict.fromkeys("abcc")
print(a)
print(b)
print(c)
print(d)
#运行结果
{'guangdong': 'guangzhou', 'hubei': 'wuhan', 'hunan': 'changsha', 'jiangsu': 'nanjing'}
{'hubei': 'good', 'guangdong': 'good', 'hunan': 'good', 'jiangsu': 'good'}
{'c': 'abc', 'b': 'abc', 'a': 'abc'}
{'c': None, 'b': None, 'a': None} #seq给出的字符串c是重复的,但是创建的键只取一个。
demo
4)get(self, k, d=None):
获取字典中键为k的值,如果字典中不包含k,则给出d值,d默认为None。
a={"a":1,"b":2,"c":3,"d":4}
b=a.get("a")
c=a.get("e")
d=a.get("e",5)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
1
None
5
demo
5)items(self):
遍历字典的一个方法,把字典中每对key和value组成一个元组,并把这些元组放在一个类似列表的dict_items中返回。
a={"a":1,"b":2,"c":3,"d":4}
b=a.items()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'c': 3, 'a': 1, 'b': 2}
dict_items([('d', 4), ('c', 3), ('a', 1), ('b', 2)]) <class 'dict_items'>
demo
6)keys(self):
遍历字典键keys的一个方法,返回一个类似列表的dict_keys,与items方法用法相同。
a={"a":1,"b":2,"c":3,"d":4}
b=a.keys()
print(a)
print(b,type(b))
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
dict_keys(['b', 'a', 'c', 'd']) <class 'dict_keys'>
demo
7)values(self):
遍历字典值value的一个方法,返回一个类似列表的dict_values,与items方法用法相同。
a={"a":1,"b":2,"c":3,"d":4}
b=a.values()
print(a)
print(b,type(b))
#运行结果
{'c': 3, 'd': 4, 'b': 2, 'a': 1}
dict_values([3, 4, 2, 1]) <class 'dict_values'>
demo
8)pop(self, k, d=None):
和get方法用法相似,只不过,get是获取字典中键为k的值,而pop是取出字典中键为k的值。当字典中不含键k时,d不是默认值时,取到的值就为d值,如果d为默认值None时,则KeyError报错。
a={"a":1,"b":2,"c":3,"d":4}
b=a.pop("a")
c=a.pop("e","five")
print(a)
print(b,type(b))
print(c,type(c))
#运行结果
{'c': 3, 'd': 4, 'b': 2}
1 <class 'int'>
five <class 'str'>
demo
9)popitem(self):
从字典中随机取出一组键值,返回一个新的元组。如果字典中无键值可取,则KeyError报错。
a={"a":1,"b":2,"c":3,"d":4}
b=a.popitem()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'b': 2, 'a': 1}
('c', 3) <class 'tuple'>
demo
10)setdefault(self, k, d=None):
从字典中获取键为k的值,当字典中包含键k值时,功能和get基本一致,当字典中不包含键k值时,在原字典上添加上键为k的初始键值对,并返回值d。
a={"a":1,"b":2,"c":3,"d":4}
b=a.setdefault("a")
c=a.setdefault("e")
d=a.setdefault("f",6)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'f': 6, 'c': 3, 'a': 1, 'e': None, 'b': 2, 'd': 4}
1
None
6
demo
11)update(self, E=None, **F):
给字典新增元素,没有返回值。用法:dict.update(dict2)。
a={"a":1,"b":2,"c":3,"d":4}
b=a.update({"e":5})
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4, 'a': 1, 'e': 5}
None
demo
12)__contains__(self, *args, **kwargs):
判断列表中是否包含某个键值对,返回布尔值。用法:dict.__contains__(keys)。
a={"a":1,"b":2,"c":3,"d":4}
b=a.__contains__("a")
print(a)
print(b)
#运行结果
{'a': 1, 'd': 4, 'c': 3, 'b': 2}
True
demo
13)__delitem__(self, *args, **kwargs):
删除字典中的某个键值对,没有返回值。用法:dict.__delitem__(keys)。
a={"a":1,"b":2,"c":3,"d":4}
b=a.__delitem__("a")
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4}
None
demo
python元组与字典的更多相关文章
- Python元组与字典详解
Python 元组 Python的元组与列表类似,不同之处在于元组的元素不能修改. 元组使用小括号,列表使用方括号. 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可. 如下实例: tup ...
- Python 学习笔记(九)Python元组和字典(一)
Python 元组 元组的定义 元组(tuple)是一种Python对象类型,元组也是一种序列 Python中的元组与列表类似,不同之处元组的元素不能修改 元组使用小括号,列表使用方括号 元组的创建 ...
- Python 学习笔记(九)Python元组和字典(三)
字典常用方法 copy() 返回一个字典的浅复制 示例:浅拷贝d.copy() 深拷贝引入import copy copy.deepcopy() >>> help(dict.co ...
- Python 学习笔记(九)Python元组和字典(二)
什么是字典 字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 键必须是唯 ...
- python元组和字典的简单学习
元组(tuple) 用圆括号()标识,定义元组后,元组元素不可修改.如果想修改元组只能重新定义元组. 因为元组不可更改,所以也没有增删改等用法,主要语法就是访问元组元素,遍历元组. 访问元组元素: t ...
- python——元组和字典类型简明理解
元组类型: 元祖创建: 不需要括号可以但是一个元素就当成了字符串类型了 >>> tup1="a"; >>> type(tup1) <cla ...
- Python 元组、字典、集合操作总结
元组 a=('a',) a=('a','b') 特点 有序 不可变,不可以修改元组的值,无法为元组增加或者删除元素 元组的创建 a=('a',) a=('a','b') tuple('abcd') 转 ...
- python 元组 列表 字典
type()查看类型 //取整除 **幂 成员运算符: in x在y序列中,就返回true 反之 not in 身份运算符: is is not 逻辑运算符 and or not 字符编码 问题 ...
- python 元组和字典中元素作为函数调用参数传递
模式1. def test1(*args): test3(*args) def test2(**kargs): test3(**kargs) def test3(a, b): print(a,b) ...
随机推荐
- ACM-ICPC 训练平台 & 比赛 分析
the file can download in https://pan.baidu.com/s/1HwoLFHGAG-boQbIn9xIhxA occ5 the article is also pu ...
- 分布式项目controller项目中web.xml配置文件的编写
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" " ...
- jQuery 事件 click() 方法,dblclick() 方法
click() 方法 当点击元素时,会发生 click 事件. 当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click. click() 方法触发 click 事件,或规定当发生 ...
- 51 eigen、boost等基础库学习
0 引言 eigen库是一个高层次的C++库,有效支持线性代数,矩阵和矢量运算,数值分析及其相关的算法.eigen除了C++标准库之外,不需要任何其他的依赖包.Eigen使用的CMake建立配置文件和 ...
- VS2010-MFC(Ribbon界面开发:使用更多控件并为控件添加消息处理函数)
转自:http://www.jizhuomi.com/software/255.html 上一节讲了为Ribbon Bar添加控件的方法.本节教程将继续完善前面的实例,讲解一些稍复杂的控件的添加方法, ...
- Openstack-L 路由注入方式
目录 目录 前言 从 Commands 到 Action 操作函数 前言 Openstack 新旧版本提供了不同的路由注入方式,也就是 Route Module 的代码方式不同,就二次开发而言用那一种 ...
- 关于Mysql分区和分表
[分区概念]分区就是把一张表的数据按照一定的规则分成多个区块,这些区块可以在同一个磁盘上,也可以在不同的磁盘上.分区后表还是一张表.分区根据一定的规则把数据文件和索引文件进行了分割,还多出了一个.pa ...
- 干货:Java正确获取客户端真实IP方法整理
在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的.但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实I ...
- 记一次java简单的if语句使用多态重构
场景描述: 一个controller中,部门领导有布置任务,查看任务整体情况,查看部门成员,查看部门成员完成情况,导出任务详情,如下: @RestController @RequestMapping( ...
- IntelliJ IDEA创建springboot项目
1.创建新项目. 2. 3.Group 是包名,Artifact是项目名. 4.springboot版本尽量选择最高版本,且不要选择SNAPSHOP版本. 5.路径可自定义,默认为D://IDEA/M ...