码迷,mamicode.com
首页 > 编程语言 > 详细

元组、列表、字典的常用方法浅释--python3.5.1版本

时间:2016-05-22 00:32:48      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:

一、元组中常用的方法

元组-->tuple(),经常用到的方法有两个

1.count()方法

>>> help(tuple.count)
Help on method_descriptor:

count(...)
    T.count(value) -> integer -- return number of occurrences of value

这个方法只向count()的括号里面传入一个参数,会返回一个整数,这个整数就是传入的参数值在元组里出现的次数,如下:

>>> tu_1=("alex","weishaopeng","a","b","c","w")
>>> tu_1.count("w")
1
>>> tu_1.count("e")
0
>>> tu_1.count("alex")
1
>>> tu_1.count("a")
1

上面的代码可以看到,当我们传入w,e,a时,它们的出现次数都是返回1,这就可以看出,元组在计算一个字母在它的所有元素中出现的次数,最小颗粒度是以元素为单位,而不是以元素里面的字母等其他值为颗粒单位,这个必须注意
2.index()方法

>>> help(tuple.index)
Help on method_descriptor:

index(...)
    T.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

 这段源码可以看到我们用index()方法时可以向index()里面传入三个参数,第一个是你要查找的这个值,第二、第三个分别是开始和结束的位置。第二、第三个参数可以不传,当它会返回一个整数,就是传入的那个值在元组里首先出现的位置

>>> tu_1=("alex","weishaopeng","a","b","c","w")
>>> tu_1.index("w")
5
ValueError: tuple.index(x): x not in tuple
>>> tu_1.index("a",0,5)
2
>>> tu_1.index("w",0,5)
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    tu_1.index("w",0,5)
ValueError: tuple.index(x): x not in tuple
>>> tu_1.index("w",0,6)
5
>>> tu_1.index("alex",0)
0

从上面的代码可以看出,这个方法执行的最小颗粒度也是元素,当只传第一、二个元素 ,不传第三个时,表示查找这个传入的元素在元组中出现的位置,从第二个参数指定的位置开始直到结尾

 二、列表中常用的方法

首先定义一个列表list_1=["a","b","c",1,2,3]

1.append()方法

Help on method_descriptor:

append(...)
    L.append(object) -> None -- append object to end

通过源码可以看到,这个方法主要是往列表里添加对象,当执行这个方法时,要往括号里传入要添加的对象,方法执行后不返回值,要添加的对象将添加在列表最后的位置

>>> list_1=["a","b","c",1,2,3]
>>> list_1.append(4)
>>> list_1
[a, b, c, 1, 2, 3, 4]
>>> list_1.append("a")
>>> list_1
[a, b, c, 1, 2, 3, 4, a]
>>> list_1.append(1)
>>> list_1
[a, b, c, 1, 2, 3, 4, a, 1]

可以看到,列表里面的元素类型没有限制,可以往列表里添加相同的元素,添加的元素在列表的最后的位置

2.clear()方法

>>> help(list.clear)
Help on method_descriptor:

clear(...)
    L.clear() -> None -- remove all items from L

这个方法主要用来清空列表里的所有元素,但是列表本身并不会被删除

>>> list_1.clear()
>>> list_1
[]
>>> del list_1
>>> list_1
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    list_1
NameError: name list_1 is not defined

可以看到当执行完这个方法后,列表list_1里面的所有元素都被清空了,然后输出list_1,变成一个空列表,但是列表还存在,当用del list_1的时候,才把整个列表删除,此时再输出list_1,就会报错,指出名为list_1 的列表没有被定义过

3.copy()方法

>>> help(list.copy)
Help on method_descriptor:

copy(...)
    L.copy() -> list -- a shallow copy of L

这个就是 列表的浅拷贝方法,如下是应用方法应用

>>> list_2=list_1.copy()
>>> list_2
[wsp, b, c, 1, 2, 3]
>>> list_1[0]="bill"
>>> list_1
[bill, b, c, 1, 2, 3]
>>> list_2
[wsp, b, c, 1, 2, 3]

 

3.count()方法  #共同方法

这个方法应用跟元组的一样,这里不再赘述

4.extend()方法

>>> help(list.extend)
Help on method_descriptor:

extend(...)
    L.extend(iterable) -> None -- extend list by appending elements from the iterable

>>> list1=[wsp, b, c, 1, 2, 3]
>>> list2=[bill, b, c, 1, 2, 3]
>>> list1.extend(list1)
>>> list1
[wsp, b, c, 1, 2, 3, wsp, b, c, 1, 2, 3]
>>> tuple1=("a","b")
>>> list1.extend(tuple1)
>>> list1
[wsp, b, c, 1, 2, 3, wsp, b, c, 1, 2, 3, a, b]
>>> s1="alex"
>>> list1.extend(s1)
>>> list1
[wsp, b, c, 1, 2, 3, wsp, b, c, 1, 2, 3, a, b, a, l, e, x]
>>> bian=1
>>> list1.extend(bian)
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    list1.extend(bian)
TypeError: int object is not iterable

这个方法是用来拓展列表的,当调用这个方法的时候,往extend()方法的括号里面传入的必须是可迭代的,当传入的是列表、元组、字符串时都可以,传入的是一个整型变量时就不可以了

5.index()#这个方法也跟元组的运用一样,共同方法

6.insert()方法

>>> help(list.insert)
Help on method_descriptor:

insert(...)
    L.insert(index, object) -- insert object before index

这个方法是用来在指定的索引位置,插入一个对象,所有传入的参数有两个,而且必须传,index就是索引位置,object就是要插入的对象,操作演示如下:

>>> list1=["a","b"]
>>> list1.insert(1,"c")
>>> list1
[a, c, b]
>>> list1.insert(4,"d")
>>> list1
[a, c, b, d]
>>> list1.insert(8,"e")
>>> list1
[a, c, b, d, e]

可以看到,第二行代码语句,在索引位置1就是列表的第2个位置插入对象"c",当索引序号超过本列表的长度时,默认往最后面插入这个对象

7.pop()方法

>>> help(list.pop)
Help on method_descriptor:

pop(...)
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.

>>> list1
[a, c, b, d, e]
>>> list1.pop()
e
>>> list1
[a, c, b, d]
>>> list1.pop(0)
a
>>> list1
[c, b, d]
>>> list1.pop(1)
b
>>> list1
[c, d]

从源码和演示中我们可以看到,调用这个pop()方法时,就是用来移除列表里面的不想要的元素,如果不传入任何参数,那么默认就移除最后那个元素,并返回这个元素。如果要指定移除某个元素,就传入这个元素的索引下标位置

8.remove()方法

>>> help(list.remove)
Help on method_descriptor:

remove(...)
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.

>>> list1
[c, d]
>>> list1=[a, c, b, d]
>>> list1.remove()
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    list1.remove()
TypeError: remove() takes exactly one argument (0 given)
>>> list1.remove(0)
Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    list1.remove(0)
ValueError: list.remove(x): x not in list
>>> list1.remove("a")
>>> list1
[c, b, d]
>>> list1=["a","b","c","d","a"]
>>> list1.remove("a")
>>> list1
[b, c, d, a]

从源码解释中可以看到,要调用这个remove()方法时(也是跟pop方法不同的地方)

1、必须传入参数

2.传入的参数必须是你要移除的那个元素,并不是那个元素的索引序号

9.reverse()方法

这个方法就是用来把列表倒序

>>> list1
[b, c, d, a]
>>> help(list.reverse)
Help on method_descriptor:

reverse(...)
    L.reverse() -- reverse *IN PLACE*

>>> list1.reverse()
>>> list1
[a, d, c, b]

 

10.sort()方法

#代码块1
>>> list1=[5,1,3,4,"a","k","f","c"]
>>> list1.sort()
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    list1.sort()
TypeError: unorderable types: str() < int()
>>> list1.sort(key=int)
Traceback (most recent call last):
  File "<pyshell#100>", line 1, in <module>
    list1.sort(key=int)
ValueError: invalid literal for int() with base 10: a
#代码块2
>>> list1=["a","k","f","c"]
>>> list1.sort()
>>> list1
[a, c, f, k]
>>> list1=["a","k","f","c"]
>>> list2=list1.sort()
>>> list2

>>> list2=sorted(list1)
>>> list2
[a, c, f, k]


从代码块1可以看到,当列表中的元素的类型不只是一种类型,比如既包含整型,又包含字符串时,那么调用sort()方法实际执行不成功,这个方法里可以设置为key=len,reverse=True,表示就是会按字符串的长度来排序,而不是顺序,同时会倒叙排序。

从代码块2可以看到,当我们想把一个排序过的列表直接赋值给一个变量时,打印输出显示为空,比如list2,那么如何实现呢,此时要用到sorted()方法,在括号里传入要排序的列表

 三、字典的常用方法

1.clear()  #这个也是跟元组、列表中的clear方法一样,表示清空字典里的元素

>>> dic1={1:"a",2:"b",3:"c",4:"d"}
>>> dic1.clear()
>>> dic1
{}


2.copy()  #跟列表中的此类方法一样,用来复制某个列表

>>> dic1={1:"a",2:"b",3:"c",4:"d"}
>>> dic2=dic1.copy()
>>> dic2
{1: a, 2: b, 3: c, 4: d}
>>> dic2[1]="k"
>>> dic2
{1: k, 2: b, 3: c, 4: d}
>>> dic1
{1: a, 2: b, 3: c, 4: d}


3.get()方法

>>> help(dict.get)
Help on method_descriptor:

get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

>>> dic1 = {name: wsp, age: 27}
>>> print ("Value : %s" %  dic1.get(Age))
Value : 27
>>> print ("Value : %s" %  dic1.get(Sex, "man"))
Value : man

从源码可以看出,调用get()方法时,可以往括号里面传入两个参数,k是指字典的键, d是指如果你传入的键不存在,那么你可以指定一个默认值,就比如上面的倒数第二行代码语句一样,要传入键"Sex",这个键在dic1 中是不存在的,但是它指定了默认值"man“,所以打印的时候就输出了此默认值

 4.keys()#这个是返回字典的键

>>> help(dict.keys)
Help on method_descriptor:

keys(...)
    D.keys() -> a set-like object providing a view on Ds keys

>>> dic1.keys()
dict_keys([Age, Name])

5.values() #用来返回字典的值

>>>dic1 = {Name: wsp, Age: 27}
>>> dic1.values()
dict_values([27, wsp])


6.items()#用来返回字典的键值对

>>> dic1 = {Name: wsp, Age: 27}
>>> dic1.items()
dict_items([(Age, 27), (Name, wsp)])

7.pop() 方法

>>> help(dict.pop)
Help on method_descriptor:

pop(...)
    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

>>> dic1.pop("Name")
wsp
>>> dic1
{Age: 27}
>>> dic1["Name"]="wsp"
>>> dic1
{Age: 27, Name: wsp}
>>> dic1.pop("sex","man")
man
>>> dic1
{Age: 27, Name: wsp}
>>> dic1.pop("school")
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    dic1.pop("school")
KeyError: school

源码的意思是这个方法也是跟元组、列表中的pop方法一样,用来移除元素的,不同的是,括号里要传入的是字典的键,如果键不存在,如果指定了默认值,那么就执行成功,并返回指定的默认值,如果键不存在,也没有指定默认值,那么就会抛出KeyError的错误

8.fromkeys()

首先定义一个迭代器,这里是一个元组

>>> tup1=(‘a‘, ‘b‘, ‘c‘)

>>> dic1=dict.fromkeys(tup1)
>>> dic1
{b: None, a: None, c: None}
>>> dic1=dict.fromkeys(tup1,10)
>>> dic1
{b: 10, a: 10, c: 10}
>>> help(dict.fromkeys)
Help on built-in function fromkeys:

fromkeys(iterable, value=None, /) method of builtins.type instance
    Returns a new dict with keys from iterable and values equal to value.

当我们要往新字典添加键值对时,可以直接以元组里的元素为键,同时在fromkeys()方法的第二个参数指定一个值,那么新字典里的所有的键的值都是第二个参数指定的值

9.popitem()

>>> dic1={Age: 27, Name: wsp}
>>> dic1.popitem()
(Age, 27)
>>> dic1.popitem()
(Name, wsp)
>>> dic1
{}
>>> dic1.popitem()
Traceback (most recent call last):
  File "<pyshell#154>", line 1, in <module>
    dic1.popitem()
KeyError: popitem(): dictionary is empty

这个方法是移除字典的键值对,移除的顺序从字典的第一个元素开始,如果字典为空,那么再执行此方法就会报字典为空的错误

10.setdefault()方法

>>> help(dict.setdefault)
Help on method_descriptor:

setdefault(...)
    D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

>>> a = { }                            #新建一个空字典
>>> a[name] = wsp             #为字典添入参数
>>> a                                    #输出字典a
{name: wsp}
>>> a.setdefault(name,alex)    #因为键名name存在,则返回键对应的值‘wsp’
wsp
>>> a.setdefault(name1,alex)  #因键名name1不存在,程序把(‘name1‘,‘alex‘)当做项添加到字典a中,并返回其值。
alex
>>> a
{name: wsp, name1: alex}


11.update()方法

>>> dic1={Age: 27, Name: wsp}
>>> dic2={name: wsp, name1: alex}
>>> dic1.update(dic2)
>>> dic1
{name: wsp, Age: 27, Name: wsp, name1: alex}

这个方法用来更新字典,从上面代码块可以看出,类似列表的extend()方法,就是把多个字典拓展添加到要更新的字典中去

 

元组、列表、字典的常用方法浅释--python3.5.1版本

标签:

原文地址:http://www.cnblogs.com/wspcoding/p/5515676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!