educoderpython入门之元组与字典_python元组与字典
一、元组
1.元组的表达
(1,2,3,4)
('olive',123)
("python",)
创建元组:
a=tuple((1,2,3,))
b=("python",)
2.元组功能属性
1 classtuple(object):2 """
3 tuple() -> empty tuple4 tuple(iterable) -> tuple initialized from iterable's items5
6 If the argument is a tuple, the return value is the same object.7 """
8 def count(self, value): #real signature unknown; restored from __doc__
9 """T.count(value) -> integer -- return number of occurrences of value"""
10 return011
12 def index(self, value, start=None, stop=None): #real signature unknown; restored from __doc__
13 """
14 T.index(value, [start, [stop]]) -> integer -- return first index of value.15 Raises ValueError if the value is not present.16 """
17 return018
19 def __add__(self, *args, **kwargs): #real signature unknown
20 """Return self+value."""
21 pass
22
23 def __contains__(self, *args, **kwargs): #real signature unknown
24 """Return key in self."""
25 pass
26
27 def __eq__(self, *args, **kwargs): #real signature unknown
28 """Return self==value."""
29 pass
30
31 def __getattribute__(self, *args, **kwargs): #real signature unknown
32 """Return getattr(self, name)."""
33 pass
34
35 def __getitem__(self, *args, **kwargs): #real signature unknown
36 """Return self[key]."""
37 pass
38
39 def __getnewargs__(self, *args, **kwargs): #real signature unknown
40 pass
41
42 def __ge__(self, *args, **kwargs): #real signature unknown
43 """Return self>=value."""
44 pass
45
46 def __gt__(self, *args, **kwargs): #real signature unknown
47 """Return self>value."""
48 pass
49
50 def __hash__(self, *args, **kwargs): #real signature unknown
51 """Return hash(self)."""
52 pass
53
54 def __init__(self, seq=()): #known special case of tuple.__init__
55 """
56 tuple() -> empty tuple57 tuple(iterable) -> tuple initialized from iterable's items58
59 If the argument is a tuple, the return value is the same object.60 # (copied from class doc)61 """
62 pass
63
64 def __iter__(self, *args, **kwargs): #real signature unknown
65 """Implement iter(self)."""
66 pass
67
68 def __len__(self, *args, **kwargs): #real signature unknown
69 """Return len(self)."""
70 pass
71
72 def __le__(self, *args, **kwargs): #real signature unknown
73 """Return self<=value."""
74 pass
75
76 def __lt__(self, *args, **kwargs): #real signature unknown
77 """Return self
78 pass
79
80 def __mul__(self, *args, **kwargs): #real signature unknown
81 """Return self*value.n"""
82 pass
83
84 @staticmethod #known case of __new__
85 def __new__(*args, **kwargs): #real signature unknown
86 """Create and return a new object. See help(type) for accurate signature."""
87 pass
88
89 def __ne__(self, *args, **kwargs): #real signature unknown
90 """Return self!=value."""
91 pass
92
93 def __repr__(self, *args, **kwargs): #real signature unknown
94 """Return repr(self)."""
95 pass
96
97 def __rmul__(self, *args, **kwargs): #real signature unknown
98 """Return self*value."""
99 pass
tuple
3.元组的部分功能属性介绍
元组和列表有很大相似性,但是元组的元素是不可修改的,所以很多列表有的功能元组都没有。
1)count(self, value):
统计元组中包含value元素的数量,返回一个int值。
1 a=(1,2,3,4,1,2,3,1,2,)2 b=a.count(1)3 print(a,type(a))4 print(b,type(b))5
6 #运行结果
7 (1, 2, 3, 4, 1, 2, 3, 1, 2)
8 3
demo
2)index(self, value, start=None, stop=None):
索引,查找元组中value元素第一个出现的位置,start与stop参数是查找起始与结束位置,默认为None,返回int数值,如果查找中不包含这个元素,则返回ValueError: 'f' is not in tuple报错。
1 a=(1,2,3,4,1,2,3,1,2,)2 b=a.index(3)3 print(a,len(a))4 print(b,type(b))5
6 #运行结果
7 (1, 2, 3, 4, 1, 2, 3, 1, 2) 9
8 2
demo
3)__add__(self, *args, **kwargs):
给元组添加一个新的元素,添加的新元素需要以元组的形式添加,生成一个新的元组。
1 a=(1,2,3,4)2 b=a.__add__((5,1)) #括号理给出的必须是元组
3 print(a,type(a))4 print(b,type(b))5
6 #运行结果
7 (1, 2, 3, 4)
8 (1, 2, 3, 4, 5, 1)
demo
4)__contains__(self, *args, **kwargs):
判断元组中是否包含某个元素,返回布尔值。
1 a=(1,2,3,4,1,2,3,1,2,)2 b=a.__contains__(2)3 c=a.__contains__(5)4 print(a)5 print(b)6 print(c)7
8 #运行结果
9 (1, 2, 3, 4, 1, 2, 3, 1, 2)10 True11 False
demo
二、字典
1.字典的表达
{"name":"olive","age":18}
创建字典:
a={"name":"olive","age":18}
b=dict({"name":"lusi","age":18})
2.字典功能属性
1 classdict(object):2 """
3 dict() -> new empty dictionary4 dict(mapping) -> new dictionary initialized from a mapping object's5 (key, value) pairs6 dict(iterable) -> new dictionary initialized as if via:7 d = {}8 for k, v in iterable:9 d[k] = v10 dict(**kwargs) -> new dictionary initialized with the name=value pairs11 in the keyword argument list. For example: dict(one=1, two=2)12 """
13 def clear(self): #real signature unknown; restored from __doc__
14 """D.clear() -> None. Remove all items from D."""
15 pass
16
17 def copy(self): #real signature unknown; restored from __doc__
18 """D.copy() -> a shallow copy of D"""
19 pass
20
21 @staticmethod #known case
22 def fromkeys(*args, **kwargs): #real signature unknown
23 """Returns a new dict with keys from iterable and values equal to value."""
24 pass
25
26 def get(self, k, d=None): #real signature unknown; restored from __doc__
27 """D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""
28 pass
29
30 def items(self): #real signature unknown; restored from __doc__
31 """D.items() -> a set-like object providing a view on D's items"""
32 pass
33
34 def keys(self): #real signature unknown; restored from __doc__
35 """D.keys() -> a set-like object providing a view on D's keys"""
36 pass
37
38 def pop(self, k, d=None): #real signature unknown; restored from __doc__
39 """
40 D.pop(k[,d]) -> v, remove specified key and return the corresponding value.41 If key is not found, d is returned if given, otherwise KeyError is raised42 """
43 pass
44
45 def popitem(self): #real signature unknown; restored from __doc__
46 """
47 D.popitem() -> (k, v), remove and return some (key, value) pair as a48 2-tuple; but raise KeyError if D is empty.49 """
50 pass
51
52 def setdefault(self, k, d=None): #real signature unknown; restored from __doc__
53 """D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"""
54 pass
55
56 def update(self, E=None, **F): #known special case of dict.update
57 """
58 D.update([E, ]**F) -> None. Update D from dict/iterable E and F.59 If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]60 If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v61 In either case, this is followed by: for k in F: D[k] = F[k]62 """
63 pass
64
65 def values(self): #real signature unknown; restored from __doc__
66 """D.values() -> an object providing a view on D's values"""
67 pass
68
69 def __contains__(self, *args, **kwargs): #real signature unknown
70 """True if D has a key k, else False."""
71 pass
72
73 def __delitem__(self, *args, **kwargs): #real signature unknown
74 """Delete self[key]."""
75 pass
76
77 def __eq__(self, *args, **kwargs): #real signature unknown
78 """Return self==value."""
79 pass
80
81 def __getattribute__(self, *args, **kwargs): #real signature unknown
82 """Return getattr(self, name)."""
83 pass
84
85 def __getitem__(self, y): #real signature unknown; restored from __doc__
86 """x.__getitem__(y) <==> x[y]"""
87 pass
88
89 def __ge__(self, *args, **kwargs): #real signature unknown
90 """Return self>=value."""
91 pass
92
93 def __gt__(self, *args, **kwargs): #real signature unknown
94 """Return self>value."""
95 pass
96
97 def __init__(self, seq=None, **kwargs): #known special case of dict.__init__
98 """
99 dict() -> new empty dictionary100 dict(mapping) -> new dictionary initialized from a mapping object's101 (key, value) pairs102 dict(iterable) -> new dictionary initialized as if via:103 d = {}104 for k, v in iterable:105 d[k] = v106 dict(**kwargs) -> new dictionary initialized with the name=value pairs107 in the keyword argument list. For example: dict(one=1, two=2)108 # (copied from class doc)109 """
110 pass
111
112 def __iter__(self, *args, **kwargs): #real signature unknown
113 """Implement iter(self)."""
114 pass
115
116 def __len__(self, *args, **kwargs): #real signature unknown
117 """Return len(self)."""
118 pass
119
120 def __le__(self, *args, **kwargs): #real signature unknown
121 """Return self<=value."""
122 pass
123
124 def __lt__(self, *args, **kwargs): #real signature unknown
125 """Return self
126 pass
127
128 @staticmethod #known case of __new__
129 def __new__(*args, **kwargs): #real signature unknown
130 """Create and return a new object. See help(type) for accurate signature."""
131 pass
132
133 def __ne__(self, *args, **kwargs): #real signature unknown
134 """Return self!=value."""
135 pass
136
137 def __repr__(self, *args, **kwargs): #real signature unknown
138 """Return repr(self)."""
139 pass
140
141 def __setitem__(self, *args, **kwargs): #real signature unknown
142 """Set self[key] to value."""
143 pass
144
145 def __sizeof__(self): #real signature unknown; restored from __doc__
146 """D.__sizeof__() -> size of D in memory, in bytes"""
147 pass
148
149 __hash__ = None
dict
3.字典的部分功能属性介绍
1)clear(self):
清除字典中的所有元素。
1 a={"name":"olive","age":18}2 b=a.clear()3 print(a)4 print(b)5
6 #运行结果
7 {}8 None
demo
2)copy(self):
复制一份元组,相当于一次浅拷贝。
1 a={"name": "olive","age":18}2 b=a.copy()3 print(a,id(a),id("name"))4 print(b,id(b),id("name"))5
6 #赋值
7 c={"name": "lusi","age":18}8 d=c9 print(c,id("name"))10 print(d,id("name"))11
12 #浅拷贝
13 e={"name": "shy","age":18}14 f=copy.copy(e)15 print(e,id(e),id("name"))16 print(f,id(f),id("name"))17
18 #运行结果
19 {'name': 'olive', 'age': 18} 2915224 2019840
20 {'name': 'olive', 'age': 18} 2915304 2019840
21 {'name': 'lusi', 'age': 18} 2019840
22 {'name': 'lusi', 'age': 18} 2019840
23 {'name': 'shy', 'age': 18} 5584616 2019840
24 {'name': 'shy', 'age': 18} 5586056 2019840
demo
3)fromkeys(*args, **kwargs):【fromkeys(seq,value=None)】
创建一个新的字典,以seq为字典的keys(键),value为字典的值,默认为None。适合创建一个一样值的字典。
1 a={"hunan": "changsha","guangdong":"guangzhou","jiangsu":"nanjing",'hubei':"wuhan"}2 b=dict.fromkeys(a,"good")3 c=dict.fromkeys(["a","b","c"],"abc")4 d=dict.fromkeys("abcc")5 print(a)6 print(b)7 print(c)8 print(d)9
10 #运行结果
11 {'guangdong': 'guangzhou', 'hubei': 'wuhan', 'hunan': 'changsha', 'jiangsu': 'nanjing'}12 {'hubei': 'good', 'guangdong': 'good', 'hunan': 'good', 'jiangsu': 'good'}13 {'c': 'abc', 'b': 'abc', 'a': 'abc'}14 {'c': None, 'b': None, 'a': None} #seq给出的字符串c是重复的,但是创建的键只取一个。
demo
4)get(self, k, d=None):
获取字典中键为k的值,如果字典中不包含k,则给出d值,d默认为None。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.get("a")3 c=a.get("e")4 d=a.get("e",5)5 print(a)6 print(b)7 print(c)8 print(d)9
10 #运行结果
11 {'b': 2, 'a': 1, 'c': 3, 'd': 4}12 1
13 None14 5
demo
5)items(self):
遍历字典的一个方法,把字典中每对key和value组成一个元组,并把这些元组放在一个类似列表的dict_items中返回。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.items()3 print(a)4 print(b,type(b))5
6 #运行结果
7 {'d': 4, 'c': 3, 'a': 1, 'b': 2}8 dict_items([('d', 4), ('c', 3), ('a', 1), ('b', 2)])
demo
6)keys(self):
遍历字典键keys的一个方法,返回一个类似列表的dict_keys,与items方法用法相同。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.keys()3 print(a)4 print(b,type(b))5
6 #运行结果
7 {'b': 2, 'a': 1, 'c': 3, 'd': 4}8 dict_keys(['b', 'a', 'c', 'd'])
demo
7)values(self):
遍历字典值value的一个方法,返回一个类似列表的dict_values,与items方法用法相同。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.values()3 print(a)4 print(b,type(b))5
6 #运行结果
7 {'c': 3, 'd': 4, 'b': 2, 'a': 1}8 dict_values([3, 4, 2, 1])
demo
8)pop(self, k, d=None):
和get方法用法相似,只不过,get是获取字典中键为k的值,而pop是取出字典中键为k的值。当字典中不含键k时,d不是默认值时,取到的值就为d值,如果d为默认值None时,则KeyError报错。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.pop("a")3 c=a.pop("e","five")4 print(a)5 print(b,type(b))6 print(c,type(c))7
8 #运行结果
9 {'c': 3, 'd': 4, 'b': 2}10 1
11 five
demo
9)popitem(self):
从字典中随机取出一组键值,返回一个新的元组。如果字典中无键值可取,则KeyError报错。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.popitem()3 print(a)4 print(b,type(b))5
6 #运行结果
7 {'d': 4, 'b': 2, 'a': 1}8 ('c', 3)
demo
10)setdefault(self, k, d=None):
从字典中获取键为k的值,当字典中包含键k值时,功能和get基本一致,当字典中不包含键k值时,在原字典上添加上键为k的初始键值对,并返回值d。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.setdefault("a")3 c=a.setdefault("e")4 d=a.setdefault("f",6)5 print(a)6 print(b)7 print(c)8 print(d)9
10 #运行结果
11 {'f': 6, 'c': 3, 'a': 1, 'e': None, 'b': 2, 'd': 4}12 1
13 None14 6
demo
11)update(self, E=None, **F):
给字典新增元素,没有返回值。用法:dict.update(dict2)。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.update({"e":5})3 print(a)4 print(b)5
6 #运行结果
7 {'c': 3, 'b': 2, 'd': 4, 'a': 1, 'e': 5}8 None
demo
12)__contains__(self, *args, **kwargs):
判断列表中是否包含某个键值对,返回布尔值。用法:dict.__contains__(keys)。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.__contains__("a")3 print(a)4 print(b)5
6 #运行结果
7 {'a': 1, 'd': 4, 'c': 3, 'b': 2}8 True
demo
13)__delitem__(self, *args, **kwargs):
删除字典中的某个键值对,没有返回值。用法:dict.__delitem__(keys)。
1 a={"a":1,"b":2,"c":3,"d":4}2 b=a.__delitem__("a")3 print(a)4 print(b)5
6 #运行结果
7 {'c': 3, 'b': 2, 'd': 4}8 None
demo
educoderpython入门之元组与字典_python元组与字典相关推荐
- python元组和列表字典_Python【列表 字典 元组】
列表 列表用中括号[ ]把各种数据框起来,每一个数据叫作"元素". 每个元素之间都要用英文逗号隔开 各种类型的数据(整数/浮点数/字符串) -------------------- ...
- python元组的方法_Python元组及其方法
""" tuple: 其实质是一个有序集合. 特点: 1.与列表相似 2.一旦初始化则不能改变 3.使用小括号() """ # 创建一个空元 ...
- python中元组的概念_python元组的概念与基本操作
元组与列表类似,关于元组同样需要做如下三点: A.概念 1.元组通过英文状态下的圆括号构成"()".其存放元素与列表一样,可以是不通的数值类型,也可以是不通的数据结构. 2.元组仍 ...
- python 类 字典_python基础类型—字典
字典 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必 ...
- python怎么打印字典_Python中的字典
作者|Ankit Gupta 编译|VK 来源|Towards Datas Science 在这篇文章中,我将讨论字典.这是"Python中的数据结构"系列的第二篇文章.本系列的第 ...
- python csv写入字典_python csv与字典操作
# encoding: utf-8 import csv d1 = {'banana':3,'apple':4,'pear':1,'orange':2} d2 = {'banana':3,'orang ...
- python 元组是什么_python元组是什么?python元组的用法介绍
本篇文章给大家带来的内容是关于python元组是什么?python元组的用法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 元组是什么? 你可以把它看作是只读的列表,因为元组不可 ...
- python元组的概念_python元组的概念知识点
{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],&q ...
- python输出字典_Python如何将字典键和值拆分为单独的列表?(代码示例)
在Python中如何将给定字典拆分为键和值的列表?下面本篇文章就来给大家介绍几种实现方法,希望对大家有所帮助.[视频教程推荐:Python教程] 方法一:使用内置函数:keys()和values() ...
最新文章
- ios中MKHorizMenu用法
- 成功解决AttributeError: Unknown property axisbg
- Android复习16【材料设计新特性:fragment、RecyclerView】
- (七)React使用
- CSS3制作一个简单的进度条
- SAP Leonardo Machine Learning处于deprecated状态的API和其替代者
- 隐私泄漏在线检测源码
- [BZOJ2502]清理雪道
- 【IPM2020】一种处理多标签文本分类的新颖推理机制
- Google Exoplayer之全面认识
- php中 被遗忘的函数
- java 进度条 百分比_java怎么让进度条带百分数
- C语言程序员面试100题,c语言面试最必考的十道试题,求职必看!!!
- JavaScript使用Modbus协议实现RTU设备连云
- jieba分词怎么操作_如何运用jieba库分词
- 【ICPC-457】数学笔记
- 关于密码测评,你必须了解的10个基本问题
- 电路单位本质与dB家族
- 全面阐述蓝牙高精度AOA定位技术原理,帮你解决蓝牙定位一切隐患-新导智能
- JIS-CTF解题思路及关键语句