python基础知识3——基本的数据类型2——列表,元组,字典,集合

时间:2023-08-07 23:39:38

磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把——整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的。

一、列表

列表是可修改可变的,有序的,可迭代的,有索引和切片,可以是任意数据类型,可以包含任意多数据

1.列表的全部方法

如:['1','2']、['wupeiqi', 'alex']

1 >>> dir(list)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

每个列表都具备如下功能:

 class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
"""在数组的末尾新增一项
def append(self, p_object): # real signature unknown; restored from __doc__
"""
L.append(object) -- append object to end """
pass def count(self, value): # real signature unknown; restored from __doc__
""" 查看lst中某一项出现的次数
L.count(value) -> integer -- return number of occurrences of value """
return 0 def extend(self, iterable): # real signature unknown; restored from __doc__
"""将原列表与其他列表扩展成新列表
L.extend(iterable) -- extend list by appending elements from the iterable """
pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""返回列表中第一个匹配项的下标,找不到会报错
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__
"""在指定位置插入项
L.insert(index, object) -- insert object before index """
pass def pop(self, index=None): # real signature unknown; restored from __doc__
"""返回指定位置的值,并将其从列表中删除。默认对末尾项操作
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass def remove(self, value): # real signature unknown; restored from __doc__
"""从列表中移除第一个符合与指定值相等的项
L.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass def reverse(self): # real signature unknown; restored from __doc__
"""列表反转
L.reverse() -- reverse *IN PLACE* """
pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
"""排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
"""
pass def __add__(self, y): # real signature unknown; restored from __doc__
""" 字符串拼接
x.__add__(y) <==> x+y """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" 判断列表中是否包含某一项
x.__contains__(y) <==> y in x """
pass def __delitem__(self, y): # real signature unknown; restored from __doc__
"""删除列表中指定下标的项
x.__delitem__(y) <==> del x[y] """
pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__
"""删除指定下标之间的内容,向下包含
x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported.
"""
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" 判断两个列表是否相等
x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" 无条件被调用,通过实例访问属性。
x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __iadd__(self, y): # real signature unknown; restored from __doc__
""" x.__iadd__(y) <==> x+=y """
pass def __imul__(self, y): # real signature unknown; restored from __doc__
"""
x.__imul__(y) <==> x*=y """
pass def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass def __mul__(self, n): # real signature unknown; restored from __doc__
""" x.__mul__(n) <==> x*n """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __reversed__(self): # real signature unknown; restored from __doc__
""" L.__reversed__() -- return a reverse iterator over the list """
pass def __rmul__(self, n): # real signature unknown; restored from __doc__
""" x.__rmul__(n) <==> n*x """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
"""
x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported.
"""
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" L.__sizeof__() -- size of L in memory, in bytes """
pass __hash__ = None list list Code

help(list)

2.列表的常用方法
 (1)append:向列表中添加项

     insert:在列表的指定位置加入值

     extend:列表的扩展;那么列表可以自己扩展自己么???当然是可以的啦!

 1 >>>
2 >>> a = [1,2,3,4]
3 >>> a.append(5)
4 >>> a
5 [1, 2, 3, 4, 5]
6 >>> b = [6,7]
7 >>> a.extend(b)
8 >>> a
9 [1, 2, 3, 4, 5, 6, 7]
10 >>> a.insert(2,0)
11 >>> a
12 [1, 2, 0, 3, 4, 5, 6, 7]
 >>> a
[1, 2, 3, 'a', 'b', 'c']
>>> b
['q', 'python']
>>> a[len(a):]=b
>>> a
[1, 2, 3, 'a', 'b', 'c', 'q', 'python']

list.extend(L) 等效于 list[len(list):] = L,L是待并入的list

(2)index:返回列表中第一个匹配项的下标

   __contain__:查看列表中是否包含某一项

   count:查看列表中某一项出现的次数

 1 >>> a
2 [1, 2, 0, 3, 4, 5, 6, 7]
3 >>> a.index(0)
4 2
5 >>> a.__contains__(7)
6 True
7 >>> a.__contains__(8)
8 False
9 >>> a.count(5)
10 1

(3)pop:删除并返回指定下标的值,默认为列表的最后一个值

   remove:删除列表中与指定值匹配的第一个值

__delitem__:删除指定下标的值

   __delslice__:删除指定下标区域内的所有值,下标向下包含

 1 >>> a
2 [1, 2, 0, 3, 4, 5, 6, 7]
3 >>> a.pop()
4 7
5 >>> a
6 [1, 2, 0, 3, 4, 5, 6]
7 >>> a.pop(2)
8 0
9 >>> a
10 [1, 2, 3, 4, 5, 6]
11 >>> a.remove(2)
12 >>> a
13 [1, 3, 4, 5, 6]
14 >>> a.__delitem__(0)
15 >>> a
16 [3, 4, 5, 6]
17 >>> a.__delslice__(0,2)
18 >>> a
19 [5, 6]

(4)reverse:列表反转,这个反转并没有什么编码顺序,就是单纯的把原来的列表从头到尾调转过来而已。。。
     sort:排序,数字、字符串按照ASCII,中文按照unicode从小到大排序。

1 >>> a = [5,4,6,8,2,6,9]
2 >>> a.sort()
3 >>> a
4 [2, 4, 5, 6, 6, 8, 9]
5 >>> a.reverse()
6 >>> a
7 [9, 8, 6, 6, 5, 4, 2]
 >>> a=[3,2,4,2,5,85,3,1]
>>> a.sort(reverse=True)
>>> a
[85, 5, 4, 3, 3, 2, 2, 1] >>> a=[3,2,4,2,5,85,3,1]
>>> sorted(a, reverse=True)
[85, 5, 4, 3, 3, 2, 2, 1]

3. “+”:字符串和列表连接

 >>> a=[1,2,3,4]
>>> s=[1,2]
>>> a+s
[1, 2, 3, 4, 1, 2]
>>>
>>> a-s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>>
>>> a='asd'
>>> s='as'
>>> a+s
'asdas'
>>> a-s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>

生成列表:Python的简洁

 >>> l = [x**2 for x in range(1,10)]
>>> l
[1, 4, 9, 16, 25, 36, 49, 64, 81]
 >>> mybag = [' glass',' apple','green leaf ']  #有的前面有空格,有的后面有空格
>>> [one.strip() for one in mybag] #去掉元素前后的空格
['glass', 'apple', 'green leaf']
enumerate

这是一个有意思的内置函数,本来我们可以通过for i in range(len(list))的方式得到一个list的每个元素编号,然后在用list[i]的方式得到该元素。如果要同时得到元素编号和元素怎么办?就是这样了:

 >>> for i in range(len(week)):
... print week[i]+' is '+str(i) #注意,i是int类型,如果和前面的用+连接,必须是str类型
...
monday is 0
sunday is 1
friday is 2

python中提供了一个内置函数enumerate,能够实现类似的功能:

 >>> for (i,day) in enumerate(week):
... print day+' is '+str(i)
...
monday is 0
sunday is 1
friday is 2

还有这个有趣的内置函数的例子:

 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

3.列表的索引和切片

 1 >>> list(range(10))
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 >>> l=list(range(10))
4 >>> l
5 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6 >>> l[:3]
7 [0, 1, 2]
8 >>> l[3:5]
9 [3, 4]
10 >>> l[-5:-3]
11 [5, 6]
12 >>> l[-5:]
13 [5, 6, 7, 8, 9]
14 >>> l[::2]
15 [0, 2, 4, 6, 8]
16 >>> (0,1,2,3,4,5,6)[:3] #元组也是列表只是不能改,所以也可以切片,得到的还是元组
17 (0, 1, 2)
18 >>> 'zhenghaolovexiaokai'[::2] #字符串可以看成列表
19 'zegalvxaki'

列表和字符串 两种类型的数据,有共同的地方,它们都属于序列(都是一些对象按照某个次序排列起来,这就是序列的最大特征),因此,就有很多类似的地方。如刚才演示的索引和切片,是非常一致的。

 >>> l=[1,2,3,4,5]
>>> l[1]
2
>>> l.index(2)
1
>>> l[1]=1 #直接赋值修改,给覆盖了
>>> l
[1, 1, 3, 4, 5]
>>> s='asdfg' #字符串不可修改
>>> s[0]='b'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>

4.通过extend()方法学习什么是可迭代的?

 help(list.extend)  #extend的参数必须是可迭代的。

 extend(...) L.extend(iterable) -- extend list by appending elements from the iterable
 >>> l=[1,2,3]
>>> s='python'
>>> lst=[7,8,9]
>>> lst.extend(l) #列表是可迭代的
>>> lst
[7, 8, 9, 1, 2, 3]
>>> lst.extend(s) 为啥?
>>> lst
[7, 8, 9, 1, 2, 3, 'p', 'y', 't', 'h', 'o', 'n']

>>> i=8     #整型不是可迭代的
   >>> lst.extend(i)
   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: 'int' object is not iterable

这就报错了。错误提示中告诉我们,那个数字 8,是 int 类型的对象,不是 iterable 的

这里用内建函数 hasattr()判断一个字符串和列表是否是可迭代的?——得出字符串不是可迭代的,而列表是可迭代的(这里不太懂,为啥字符串不是可迭代的呢,和上面矛盾啊)

 >>> str='python'
>>> hasattr(str,'__iter__')
False
>>> lst=[1,2]
>>> hasattr(lst,'__iter__')
True

hasattr()的判断本质就是看那个类型中是否有__iter__函数。还可以用 dir()找一找,在数字、字符串、列表中,谁有__iter__。同样还可找一找 元组,字典两种类型对象是否含有这个方法。

5.列表重要特征:

列表是可以修改的。这种修改,不是复制一个新的,而是在原地进行修改。

没有返回值,即不能赋值给某个变量。

 >>> lst=[7,8,9]
>>> id(lst)
139795244578144
>>> lst.append(5)
>>> lst
[7, 8, 9, 5]
>>> id(lst)
139795244578144
 >>> a=[1,2,3]
>>> b=a.extend([4,5,6]) #a原地修改了,没有返回值
>>> b #所以b什么也没有得到
>>> a
[1, 2, 3, 4, 5, 6]

6.列表生成式

1 >>> [x*x for x in range(1, 11) if x%2==0]
2 [4, 16, 36, 64, 100]
3 >>> [m+n for m in 'abc' for n in 'asd'] #两层循环
4 ['aa', 'as', 'ad', 'ba', 'bs', 'bd', 'ca', 'cs', 'cd']

7.字符串和列表比较

都属于序列类型的数据,很多方法很类似总结

list 和 str 的最大区别是:list 是可以改变的,str 不可变

二、元组

元组是不可修改不可变的,有序的,可迭代的,有索引和切片

1.元组的全部方法

如:(11,22,33)、('zhenghao', 'xiaokai')

1 1 >>> dir(tuple)
2 2 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] 
 Help on class tuple in module __builtin__:

 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.
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __getnewargs__(...)
|
| __getslice__(...)
| x.__getslice__(i, j) <==> x[i:j]
|
| Use of negative indices is not supported.
|
| __gt__(...)
| x.__gt__(y) <==> x>y
|
| __hash__(...)
| x.__hash__() <==> hash(x)
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __le__(...)
| x.__le__(y) <==> x<=y
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __lt__(...)
| x.__lt__(y) <==> x<y
|
| __mul__(...)
| x.__mul__(n) <==> x*n
|
| __ne__(...)
| x.__ne__(y) <==> x!=y
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| __rmul__(...)
| x.__rmul__(n) <==> n*x
|
| count(...)
| T.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| T.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T None

2.元组和字符串,列表的比较

tuple 是一种序列类型的数据,这点上跟 list/str 类似。它的特点就是其中的元素不能更改,所以也就没有添加,删除,修改等方法,这点上跟列表不同,倒是跟字符串类似;它的元素又可以是任何类型的数据,这点上跟 list 相同,但不同于 str。

 >>> tup=(1, 'python', [3,4], (5,6)) #元组的元素可以任意类型,和列表类似
>>> tup[1] #元组的索引,是序列类型
'python'
>>> tup[1]=2 #元组元素不可原地修改,和字符串类似
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tup.append(2) #元素不可更改,没有此方法,和str类似
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

>>> tup[2][0] 
   3
   >>> tup[2].append(5) #元组的元素之一为列表,所以通过修改列表,元组样子改变了,但是注意元组的元素还不没变
   >>> tup
   (1, 'python', [3, 4, 5], (5, 6))

 

3.元组的索引和切片

4.tuple 用在哪里?

既然它是 list 和 str 的杂合,它有什么用途呢?不是用 list 和 str 都可以了吗?

在很多时候,的确是用 list 和 str 都可以了。但是,看官不要忘记,我们用计算机语言解决的问题不都是简单问题,就如同我们的自然语言一样,虽然有的词汇看似可有可无,用别的也能替换之,但是我们依然需要在某些情况下使用它们.

一般认为,tuple 有这类特点,并且也是它使用的情景:

  • Tuple 比 list 操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用 tuple 代替 list。
  • 如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用 tuple 而不是 list 如同拥有一个隐含的 assert 语句,说明这一数据是常量。如果必须要改变这些值,则需要执行 tuple 到 list 的转换 (需要使用一个特殊的函数)。
  • Tuples 可以在 dictionary(字典,后面要讲述) 中被用做 key,但是 list 不行。Dictionary key 必须是不可变的。Tuple 本身是不可改变的,但是如果您有一个 list 的 tuple,那就认为是可变的了,用做 dictionary key 就是不安全的。只有字符串、整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key。
  • Tuples 可以用在字符串格式化中。

三、字典

字典是可修改可变的,无序的,无索引和切片,可迭代的,键不可以是可变的(list,dict)而且不能重复(键都是唯一的),值可以是任意类型,可存储任意多的对象

dict(dictory)也被称为关联数组或哈希表

1.字典的全部方法

如:{'name': 'zhenghao', 'age': 18} 、{'host': '127.0.0.1', 'port': 8000]}

1 >>> dir(dict)
2 ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

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(S, v=None): # real signature unknown; restored from __doc__
"""
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
"""
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取值,d是默认值 """
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def has_key(self, k): # real signature unknown; restored from __doc__
""" 是否有key """
""" D.has_key(k) -> True if D has a key k, else False """
return False def items(self): # real signature unknown; restored from __doc__
""" 所有项的列表形式 """
""" D.items() -> list of D's (key, value) pairs, as 2-tuples """
return [] def iteritems(self): # real signature unknown; restored from __doc__
""" 项可迭代 """
""" D.iteritems() -> an iterator over the (key, value) items of D """
pass def iterkeys(self): # real signature unknown; restored from __doc__
""" key可迭代 """
""" D.iterkeys() -> an iterator over the keys of D """
pass def itervalues(self): # real signature unknown; restored from __doc__
""" value可迭代 """
""" D.itervalues() -> an iterator over the values of D """
pass def keys(self): # real signature unknown; restored from __doc__
""" 所有的key列表 """
""" D.keys() -> list of D's keys """
return [] 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__
""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
""" 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
""" 更新
{'name':'alex', 'age': 18000}
[('name','sbsbsb'),]
"""
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, 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() -> list of D's values """
return [] def viewitems(self): # real signature unknown; restored from __doc__
""" 所有项,只是将内容保存至view对象中 """
""" D.viewitems() -> a set-like object providing a view on D's items """
pass def viewkeys(self): # real signature unknown; restored from __doc__
""" D.viewkeys() -> a set-like object providing a view on D's keys """
pass def viewvalues(self): # real signature unknown; restored from __doc__
""" D.viewvalues() -> an object providing a view on D's values """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __contains__(self, k): # real signature unknown; restored from __doc__
""" D.__contains__(k) -> True if D has a key k, else False """
return False def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
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): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None dict dict code

help(dict)

字典是python数据类型中的一大亮点,在其中占有着独特的地位,在这里先介绍一下字典的特性,和list不同,字典是无序的,没有索引和切片,它依靠key和value之间的联系进行索引,由于这种特殊的索引方式,字典中不可以有重复的key。

(1)keys/values/items:取所有字典的key/取所有字典的value/取所有字典的key,value

 >>> dic={'name':'zhenghao', 'age':20}
>>> dic.keys()
['age', 'name']
>>> dic.values()
[20, 'zhenghao']
>>> dic.items()
[('age', 20), ('name', 'zhenghao')]

(2)已知key的情况下,获取value的值时可以使用‘字典名[key值]’的方法,在循环遍历中,尽管字典提供了for k,v in dic.items()的方法,但是为了避免占用内存空间,我们还是遍历key,再利用key的值就可以获取到value啦!

    get:字典名[key值]的方式有一点弊端,那就是当key值不存在的时候会报错,这个时候我们使用get方法,可以避免报错的情况

 >>> dic={'name':'zhenghao', 'age':20}
>>> for n in dic: #循环时默认循环的是keys
... print 'key:', n, 'value:', dic[n]
...
key: age value: 20
key: name value: zhenghao
>>> dic['name']
'zhenghao'
>>> dic['score'] #会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'score'
>>> dic.get('name')
'zhenghao'
>>> dic.get('score') #不会报错
>>>
17 >>>dic.get('score', -1) #不会报错,默认-1
18 -1
19 >>>'score' in dic #也不会报错
20 False

(3)clear:清空字典

 >>> dic.get('score')
>>> dic={'name':'zhenghao', 'age':20}
>>> dic.clear()
>>> dic
{}
>>>

(4)pop:根据指定的key删除一组数据

   popitem:随机的删除一组数据。。。我觉得这就是python在逗我。。。

(5)setdefault:dic.setdefault[key1],key1存在,则返回value1,不存在,则自动创建value = 'None'

 >>> dic={'name':'zhenghao'}
>>> dic.setdefault('name')
'zhenghao'
>>> dic.setdefault('age')
>>> dic
{'age': None, 'name': 'zhenghao'}
>>>

(6)update:dict1.update(dict2),判断dict2中的每一个key在dict1中是否存在,存在:就将dict1中的value更新成dict2中的,不存在:将key和value都复制过去

 1 >>> dic
2 {'age': None, 'name': 'E'}
3 >>> dic1 = dic
4 >>>
5 >>> dic1
6 {'age': None, 'name': 'E'}
7 >>> dic2 = {'age': 18, 'name': 'E','gender':'female'}
8 >>> dic1.update(dic2)
9 >>> dic1
10 {'name': 'E', 'gender': 'female', 'age': 18}

(7)fromkeys:可以通过list或元组创建一个字典,

  dict.fromkeys([1,2,3],'test'),可以创建一个字典,但是如果a.fromkeys([1,2,3],[]},创建的字典的值都是一个空列表,那么其中一个列表的值发生了变化,所有的列表都会跟着发生变化,因为这个方法就是很傻很天真的把所有value的指针指向了同一个列表。所以感觉这个方法也是逗我玩儿的。。。

>>> a = dict.fromkeys([1,2,3],'test')
>>> a
{1: 'test', 2: 'test', 3: 'test'}
>>> a = dict.fromkeys([1,2,3],[])
>>> a[1].append('test')
>>> a
{1: ['test'], 2: ['test'], 3: ['test']}

3.字典可以嵌套:

 >>> a_list = [[1,2,3],[4,5],[6,7]]
>>> a_list[1][1]
5
>>> a_dict = {1:{"name":"qiwsir"},2:"python","email":"qiwsir@gmail.com"}
>>> a_dict
{1: {'name': 'qiwsir'}, 2: 'python', 'email': 'qiwsir@gmail.com'}
>>> a_dict[1]['name'] #一个嵌套的dict访问其值的方法:一层一层地写出键
'qiwsir

4.获取键、值

在上一讲中,已经知道可以通过dict的键得到其值。例上面的例子。

还有别的方法得到键值吗?有!python一般不是只有一个方法实现某个操作的

从上面的结果中,我们就可以看出,还可以用for语句循环得到相应内容。例如:

以下两种方法等效:

 >>> for value in website.values():
... print value
...
google
baidu
facebook
4 >>> for key in website:
... print website[key]
...
google
baidu
facebook
4

下面的方法又是等效的:

 >>> for k,v in website.items():
... print str(k)+":"+str(v)
...
1:google
second:baidu
3:facebook
twitter:4 >>> for k in website:
... print str(k)+":"+str(website[k])
...
1:google
second:baidu
3:facebook
twitter:4

下面的方法也能得到键值,不过似乎要多敲键盘

 >>> website
{1: 'google', 'second': 'baidu', 3: 'facebook', 'twitter': 4}
>>> website.get(1)
'google'
>>> website.get("second")
'baidu'

3.字典可以原地修改

 >>> dic={}
>>> id(dic)
139795272803784
>>> dic['name']='zhenghao' #直接给键值
>>> dic
{'name': 'zhenghao'}
>>> id(dic)
139795272803784
>>>

3.字典的几种创建方法

 >>> dic={}  1 #空字典,原地修改,往里面添键值
>>> dic
{}
>>>
>>> dic['name']='zhenghao'
>>> dic
{'name': 'zhenghao'}
>>>
>>> dic2={'name':'zhenghao', 'age':20} 2 #直接给键值
>>> dic2
{'age': 20, 'name': 'zhenghao'}
>>>
>>> dic3=(['name', 'zhenghao'], ['age', '20']) 3 #用dict()方法,利用元组构造字典
>>> ifo=dict(dic3)
>>> ifo
{'age': '', 'name': 'zhenghao'}
>>>
>>> ifo=dict(name='zhenghao', age=20) #用dict()方法
>>> ifo
{'age': 20, 'name': 'zhenghao'}
>>>
>>> ifo={}.fromkeys(('name1', 'name2'), 'zhenghao') 4 #用fromkeys()方法,注意:这种方法是重新建立一个dict
>>> ifo
{'name2': 'zhenghao', 'name1': 'zhenghao'}
>>>
>>> ifo={}.fromkeys(['name1', 'name2'], 'zhenghao')
>>> ifo
{'name2': 'zhenghao', 'name1': 'zhenghao'}
>>>
>>> dic3={(1,2):1} #在字典中的键必须是不可变数据,值可以是任何类型
>>> dic3
{(1, 2): 1}
>>>
>>> dic3={[1,2]:1} #这里列表不可以做字典的键,因为是可变的数据类型,列表和字典是可变的,整数和字符串和元组都是不可变的
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>

>>> dic3={{'s':2}:1}
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'dict'

4.字典练习题

1 练习:元素分类
2 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于等于 66 的值保存至第二个key的值中。
3 即: {'k1': 大于66 , 'k2': 小于等于66}

回答:

a=[11,22,33,44,55,66,77,88,99,90]
dict1={'k1':[],'k2':[]} for i in a:
if i >66:
dict1['k1'].append(i)
else:
dict1['k2'].append(i)
print dict1 最好的是用下面的方法来动态的扩展字典:
a=[11,22,33,44,55,66,77,88,99,90]
dict1={} #动态的增加字典 for i in a:
if i >66:
if 'k1' in dict1.keys():
dict1['k1'].append(i)
else:
dict1['k1'] = [i,]
else:
if 'k2' in dict1.keys():
dict1['k2'].append(i)
else:
dict1['k2'] = [i,]
print dict1

四、set集合


集合是不可重复的(dict的键),有的可修改可变,有的不可修改不可变(冷冻的集合),无序的,无索引和切片,无序的

1.集合的全部方法

set是一个无序且不重复的元素集合

1 >>> dir(set)
2 ['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
3 >>>

2.集合的常用方法(可修改可变的):

1.add():

 >>> a_set = {}       #我想当然地认为这样也可以建立一个set
>>> a_set.add("q") #报错.看看错误信息,居然告诉我dict没有add.我分明建立的是set呀.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'add'
>>> type(a_set) #type之后发现,计算机认为我建立的是一个dict
<type 'dict'>

特别说明一下,{ }这个东西,在dict和set中都用.但是,如上面的方法建立的是dict,不是set.这是python规定的.要建立set,只能用下面介绍的方法了

2.update():合并

 >>> a={1,2}
>>> s={'a','s'}
>>> a.update(s)
>>> a
set(['a', 1, 2, 's'])
>>> s
set(['a', 's'])
>>>

3.pop():删除任意一个

 >>> s={1,2,3,'qer'}
>>> s.pop()
3
>>> s
set([1, 2, 'qer'])
>>> s.pop()
1
>>> s
set([2, 'qer'])
>>>

4.remove():删除指定元素

>>> s={1,2,3,'qer'}
>>> s.remove(1)
>>> s
set([3, 2, 'qer'])
>>> s.remove('qer')
>>> s
set([3, 2])
>>>

5.clear():删除所有

 >>> s={1,2,3,'qer'}
>>> s.clear()
>>> s
set([])
>>>

2.集合的创建

set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。它的特点是:有的可变,有的不可变;元素无次序,不可重复。无序所以没有索引不能切片。

 >>> s=set('zhenghao') 2 #用set()方法创建
>>> s
set(['a', 'e', 'g', 'h', 'o', 'n', 'z']) #可看出集合是不可重复的,无序的
>>>
>>> s2=set([20, 'zhenghao', 20, 'xiaokai']) #用list创建集合,元素可以是int,str,tuple不可变的
>>> s2
set(['zhenghao', 20, 'xiaokai'])
>>>
>>> s3={'zhenghao', 20} #直接用{}创建
>>> s3
set(['zhenghao', 20])

3.集合里的元素应该都是不可变的

 >>> s={2, 'zheng', [1,2,3], (3,4,5)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list' #集合元素有列表,列表是可变的,所以报错
>>>
>>> s={2, 'zheng', (3,4,5), {1:2,'d':4}}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict' #字典也是可变的,不可哈希”(unhashable)就是其可变,如 list/dict,都能原地修改
>>>

4.集合是无序的,没有索引

 >>> s={2, 'zheng', (3,4,5)}
>>> s[1]='xiao' #集合没有索引值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support item assignment
>>>

set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:

 >>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

冷冻的集合,集合的运算等http://www.lai18.com/content/384856.html