python(18):遍历、公共方法、引用、可变与不可变类型

一、遍历

通过for ... in ...:的语法结构,我们可以遍历字符串、列表、元组、字典等数据结构。

1.字符串遍历

>>> a_str = "hello itcast"
>>> for char in a_str:
...     print(char,end=' ')
...
h e l l o   i t c a s t

 

2.列表遍历

>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
...     print(num,end=' ')
...
1 2 3 4 5

 

3.元组遍历

>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
...     print(num,end=" ")
1 2 3 4 5

 

4.字典遍历

(1) 遍历字典的key(键)

chars = {'a':1,'b':2,'c':3,'d':4}

for i in chars:
    print(i)
#只默认循环输出所有的key值

for i in chars.keys():
    print(i)
#循环输出所有的key值

(2) 遍历字典的value(值)

chars = {'a':1,'b':2,'c':3,'d':4}

for i in chars.values():
    print(i)
#循环输出所有的key值

(3) 遍历字典的key-value(键值对)

chars = {'a':1,'b':2,'c':3,'d':4}

for k,v in chars.items():
    print(k,v)
#循环输出所有的键值对

想一想,如何实现带下标索引的遍历

方法一:

>>> chars = ['a', 'b', 'c', 'd']
>>> i = 0
>>> for chr in chars:
...     print("%d %s"%(i, chr))
...     i += 1
...
0 a
1 b
2 c
3 d

方法二:使用enumerate()

>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
...     print i, chr
...
0 a
1 b
2 c
3 d

 

二、公共方法

1.运算符

(1)+

>>> "hello " + "itcast"
'hello itcast'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

(2)*

>>> 'ab'*4
'ababab'
>>> [1, 2]*4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b')*4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

(3)in

注意:in在对字典操作时,判断的是字典的键

>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True

 

2.python内置函数

Python包含了以下内置函数

(1)cmp

注意:cmp在比较字典数据时,先比较键,再比较值。

>>> cmp("hello", "itcast")
-1
>>> cmp("itcast", "hello")
1
>>> cmp("itcast", "itcast")
0
>>> cmp([1, 2], [3, 4])
-1
>>> cmp([1, 2], [1, 1])
1
>>> cmp([1, 2], [1, 2, 3])
-1
>>> cmp({"a":1}, {"b":1})
-1
>>> cmp({"a":2}, {"a":1})
1
>>> cmp({"a":2}, {"a":2, "b":1})
-1

(2)len

注意:len在操作字典数据时,返回的是键值对个数。

>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2

(3)max

>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'

(4)del

del有两种用法,一种是del加空格,另一种是del()

>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

 

3.多维列表/元祖访问的示例

>>> tuple1 = [(2,3),(4,5)]
>>> tuple1[0]
(2, 3)
>>> tuple1[0][0]
2
>>> tuple1[0][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> tuple1[0][1]
3
>>> tuple1[2][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> tuple2 = tuple1+[(3)]
>>> tuple2
[(2, 3), (4, 5), 3]
>>> tuple2[2]
3
>>> tuple2[2][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

 

三、引用

在python中,值是靠引用来传递来的。我们可以用id()来判断两个变量是否为同一个值的引用。 我们可以将id值理解为那块内存的地址标示。

>>> a = 1
>>> b = a
>>> id(a)
13033816
>>> id(b)   # 注意两个变量的id值相同
13033816
>>> a = 2
>>> id(a)   # 注意a的id值已经变了
13033792
>>> id(b)   # b的id值依旧
13033816


>>> a = [1, 2]
>>> b = a
>>> id(a)
139935018544808
>>> id(b)
139935018544808
>>> a.append(3)
>>> a
[1, 2, 3]
>>> id(a)
139935018544808
>>> id(b)       # 注意a与b始终指向同一个地址
139935018544808

 

四、可变类型与不可变类型

1.可变类型,值可以改变:

(1)列表 list

(2)字典 dict

 

2.不可变类型,值不可以改变:

(1)数值类型 int, long, bool, float

(2)字符串 str

(3)元组 tuple

猜你喜欢

转载自blog.csdn.net/qq_31655771/article/details/81297550