Python中的元组及字典常用方法举例

1.元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

    元组和列表十分相似

    元组和字符串一样是不可以变的。

  • 元组可以存储一系列的值
  • 元组通常用在用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

如下实例:

>>> t = (1,3,5,'a',(1,))
>>> type(t)
<class 'tuple'>
>>> print(t)
(1, 3, 5, 'a', (1,))

创建空元组

tup1 = ();

元组中只包含一个元素时,需要在元素后面添加逗号

tup1 = (50,);

元组操作:

    元组和字符串一样属于序列类型,可以通过索引和切片操作

    元组值不可变

    无组的拆分

>> t = (1,2,3)
>>> a,b,c = t
>>> print(t)
(1, 2, 3)
>>> print(a)
1
>>> print(b+c)
5
>>> t = (1,3,5,'a',(1,))
>>> type(t)
<class 'tuple'>
>>> print(t)
(1, 3, 5, 'a', (1,))
>>> print(t[1])
3

元组中引用变量:

>>> print(t)
(1, 2, 3)
>>> t1 = (t,4,5,"abc")
>>> print(t1)
((1, 2, 3), 4, 5, 'abc')

元组切片:    

>>> t1 = (t,4,5,"abc")
>>> print(t1)
((1, 2, 3), 4, 5, 'abc')
>>> x,y,z,m = t1
>>> print(x)
(1, 2, 3)
>>> print(m)
abc

  元组的方法:

(1) index()方法:查看元素下标是多少 

>>> t = (1,3,5,6,6,7,7,8)
>>> t.index(3)
1
>>> t.index(8)
7

  (2) conunt()方法:统计某无素的个数   

>>> t = (1,3,5,6,6,7,7,8)
>>> t.count(6)
2
>>> t.count(8)
1
元组中的内置函数:
1len(tuple)
计算元组元素个数。
2max(tuple)
返回元组中元素最大值。
3min(tuple)
返回元组中元素最小值。
4tuple(seq)
将列表转换为元组。

举例如下:

>>> tuple1 = (1,2,3)
>>> tuple2 = (2,3,4,5)
>>> len(tuple1)
3
>>> max(tuple1)
3
>>> min(tuple1)
1

>>> list = [1,3,5,6,7]
>>> tuple(list)
(1, 3, 5, 6, 7)
>>> list
[1, 3, 5, 6, 7]

 

2.字典

字典是python中的唯一的映射类型(哈希表)

字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

字典的方法

  •     keys()
  •     values()
  •     get()
  •     items()

举例如下:    

>>> dic = {'a':1,'b':2}
>>> dic
{'a': 1, 'b': 2}

>>> dic.keys()
dict_keys(['a', 'b'])

>>> dic.values()
dict_values([1, 2])

>>> len(dic)
2

>>> dic = {'a':1,'b':2}
>>> dic.get('b')
2

>>> dic["b"]
2

更改字典内value:

>>> dic
{'a': 1, 'b': 2}
>>> dic['a'] = 8
>>> dic
{'a': 8, 'b': 2}

查看key是不是在字典里    

>>> dic
{'a': 1, 'b': 2}
>>> 'b' in dic
True
>>> "c" in dic
False

变为列表:

>>> dic
{'a': 8, 'b': 2}
>>> dic.items()
dict_items([('a', 8), ('b', 2)])

复制字典:    

>>> dic
{'a': 8, 'b': 2}
>>> dic1 = dic.copy()
>>> dic1
{'a': 8, 'b': 2}

删除字典内容:

>>> dic
{'a': 8, 'b': 2}
>>> dic.pop("a")
8
>>> dic
{'b': 2}

更新字典,两个字典更新为一个:

>>> dic
{'b': 2}
>>> dic1
{'a': 8, 'b': 2}
>>> dic.update(dic1)
>>> dic
{'b': 2, 'a': 8}

创建字典:

>>> dic = {}

>>> dic = dict()

>>> dict(a=1,b=2)
{'a': 1, 'b': 2}

>>> dict((["c",3],["d",4]))
{'c': 3, 'd': 4}

#fromkeys(),字典元素有相同的值时,默认为None.
>>> dic.fromkeys('abcd') 
{'a': None, 'b': None, 'c': None, 'd': None}

#自动生成100个key,value默认为100
dic.fromkeys(range(100),100)
{0: 100, 1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 10.....100:100}

访问字典:

>>> dic1
{'a': 8, 'b': 2}
>>> dic["b"]
2

    for循环访问:

>>> for k,v in dic1.items():print(k,v)
... 
a 8
b 2

 

Python3中常用的方法:

 帮助信息

  • help()查看帮助信息
>> help(list)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
  • dir() 看当前环境中变量
>>> dir()
['__builtins__', 'a', 'b', 'c', 'dic', 'dic1', 'django', 'django_manage_shell', 'i', 'input', 'k', 'list', 'm', 'sys', 't', 't1', 'tuple1', 'tuple2', 'v', 'x', 'y', 'z']

类型转换:

  • str()  
  • int()   
  • list()  
  • dict()  
  • tuple()

自动生成序列:

  range()          

>>> for i in range(10):print(i)
... 
0
1
2
3
4
5
6
7
8
9

       

可迭代的,循环取值

    items()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = {1:1,2:2,3:3}
for i in list1.items():
    print(i)


#结果:
(1, 1)
(2, 2)
(3, 3)

默认输入都为字符串:

  input ()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------

x = input("x = ")
print(x)

  

求长度:

    len()

>>> list
[1, 3, 5, 6, 7]
>>> len(list)
5

看类型:

    type()

>>> type(list)
<class 'list'>

a是不是什么类型

 

    isinstance(a,list)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = [1,3,5]
print(list1)
a=isinstance(list1,list)
print(a)

#结果
[1, 3, 5]
True

有没有某属性

    print(hasttr(l1,"append"))

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
list1 = [1,3,5]
print(list1)
a=hasattr(list1,"append")
print(a)

#结果
[1, 3, 5]
True

 

打印结果:

    print()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/1 21:56
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------
a="hello fengxiaoqing"
print(a)

#结果:
hello fengxiaoqing

生成可迭代列表,(index,value)

    enumerate()

>>> for i in enumerate(list):
...     print(i)
...         
(0, 1)
(1, 3)
(2, 5)
(3, 6)
(4, 7)

 

转载于:https://my.oschina.net/u/3804957/blog/1788302

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值