目录
1. 课程目标
2. for循环
2.1 基本形式
示例
>>> h = 'hello'
>>> for i in h:
print(i)
h
e
l
l
o
>>> lst = [1, 2, 3, 4]
>>> for i in lst:
print(i)
1
2
3
4
>>> t = tuple(lst)
>>> t
(1, 2, 3, 4)
>>> for i in t:
print(i)
1
2
3
4
>>>
通过for循环获得字典中键值对的键和值
>>> d = {'name':'zhangsan', 'lang':'python', 'age':39}
>>> for k in d:
print(k)
name
lang
age
>>> for k in d:
print(k, d[k])
name zhangsan
lang python
age 39
>>>
通过字典中的items()方法获取键值对的键和值
>>> d
{'name': 'zhangsan', 'lang': 'python', 'age': 39}
>>> d.items()
dict_items([('name', 'zhangsan'), ('lang', 'python'), ('age', 39)])
>>> for k, v in d.items():
print(k, v)
name zhangsan
lang python
age 39
>>>
整数为不可迭代对象
>>> for i in 325:
print(i)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
for i in 325:
TypeError: 'int' object is not iterable
>>>
通过内置函数hasattr()函数判断对象是否为可迭代对象,其中值为’iter’方法
可迭代对象中都有"iter"方法
用于for循环的都是可迭代对象
>>> d
{'name': 'zhangsan', 'lang': 'python', 'age': 39}
>>> hasattr(d, '__iter__')
True
>>> hasattr(325, '__iter__')
False
>>>
通过collections.abc模块中的isinstance()来判断对象是否为可迭代对象
本质上通过isinstance()来判断某一个对象是否为某一个类的实例
示例,python3.8版本将停止运行该方法
>>> import collections
>>> isinstance(325, collections.Iterable)
Warning (from warnings module):
File "<pyshell#40>", line 1
DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working
False
>>>
示例
判断325是否是collections.abc.Iterable类的实例
>>> import collections.abc
>>> isinstance(325, collections.abc.Iterable)
False
>>>
2.2 相关函数
2.2.1 range函数
range()函数
[, step]代表可以省略 ,如果加上时,不能忘记添加逗号
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
|
| Methods defined here:
|
| __bool__(self, /)
| self != 0
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(...)
| Return a reverse iterator.
|
| count(...)
| rangeobject.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| rangeobject.index(value) -> integer -- return index of value.
| Raise ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| start
|
| step
|
| stop
>>>
示例
使用range()时,当a未被使用时,不像list那样占据内存,因此range的值可以设很大
>>> a = range(10)
>>> a
range(0, 10)
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = range(1, 22, 2)
>>> list(b)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
>>>
range()函数使用示例
使用range()函数获取100以内的偶数
>>> for i in range(100):
if i % 2 == 0: print(i)
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
>>>
将100以内的偶数添加到列表中
>>> lst = []
>>> lst
[]
>>> for i in range(100):
if i % 2 ==0:
lst.append(i)
>>> lst
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
>>> list(range(0, 100,2))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
>>>
2.2.2 zip()函数
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> z = zip(a, b)
>>> z
<zip object at 0x00000193430C4300>
>>> list(zip(a, b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> dict(zip(a, b))
{1: 5, 2: 6, 3: 7, 4: 8}
>>>
通过zip实现两个相同长度列表的元素相加取和
>>> a
[1, 2, 3, 4]
>>> b
[5, 6, 7, 8]
>>> for i in range(len(a)):
print(a[i] + b[i])
6
8
10
12
>>> lst = []
>>> for x, y in zip(a, b):
lst.append(x + y)
>>> lst
[6, 8, 10, 12]
>>>
>>> m = [1, 2, 3]
>>> n = [3, 4, 5, 6]
>>> list(zip(m,n))
[(1, 3), (2, 4), (3, 5)]
>>>
2.2.3 enumerate()函数
>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> for i in range(len(seasons)):
print(i , seasons[i])
0 spring
1 summer
2 fall
3 winter
>>> list(enumerate(seasons))
[(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
>>> for i, e in enumerate(seasons):
print(i, e)
0 spring
1 summer
2 fall
3 winter
>>>
3. 列表解析
列表解析的运算速度比for循环的速度要快
后面的是列表解析
列表解析示例二
>>> a
[1, 2, 3, 4]
>>> b
[5, 6, 7, 8]
>>> [x+y for x, y in zip(a, b)]
[6, 8, 10, 12]
>>>
4. 其他解析
5. 例题1:使用列表解析统计字符串中每个单词的数量。
5.1 题目:
统计如下字符串中每个单词的数量。
——song = “When I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountainis You raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains You raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains”
5.2 程序代码
song = """When I am down and oh my soul so weary
When troubles come and my heart burdened be
Then I am still and wait here in the silence
Until you come and sit awhile with me
You raise me up so I can stand on mountainis
You raise me up to walk on stormy seas
I am strong when I am on your shoulders
You raise me up to more than I can be
You raise me up so I can stand on mountains
You raise me up to walk on stormy seas
I am strong when I am on your shoulders
You raise me up to more than I can be
You raise me up so I can stand on mountains"""
print(song)
slst = song.split()
print(slst)
d = {}
for word in slst:
# 有的单词存在大小写,将单词统一转为小写
word = word.lower()
if word in d:
d[word] += 1
else:
# 如果该单词从未在字典d中出现过,则将该单词以键值对(word:1)的方式存进字典中
d[word] = 1
print(d)
5.3 运行结果
C:\Users\邢程\AppData\Local\Programs\Python\Python38\python.exe "D:/Python 项目/入门/1.3.3_for_example01.py"
When I am down and oh my soul so weary
When troubles come and my heart burdened be
Then I am still and wait here in the silence
Until you come and sit awhile with me
You raise me up so I can stand on mountainis
You raise me up to walk on stormy seas
I am strong when I am on your shoulders
You raise me up to more than I can be
You raise me up so I can stand on mountains
You raise me up to walk on stormy seas
I am strong when I am on your shoulders
You raise me up to more than I can be
You raise me up so I can stand on mountains
['When', 'I', 'am', 'down', 'and', 'oh', 'my', 'soul', 'so', 'weary', 'When', 'troubles', 'come', 'and', 'my', 'heart', 'burdened', 'be', 'Then', 'I', 'am', 'still', 'and', 'wait', 'here', 'in', 'the', 'silence', 'Until', 'you', 'come', 'and', 'sit', 'awhile', 'with', 'me', 'You', 'raise', 'me', 'up', 'so', 'I', 'can', 'stand', 'on', 'mountainis', 'You', 'raise', 'me', 'up', 'to', 'walk', 'on', 'stormy', 'seas', 'I', 'am', 'strong', 'when', 'I', 'am', 'on', 'your', 'shoulders', 'You', 'raise', 'me', 'up', 'to', 'more', 'than', 'I', 'can', 'be', 'You', 'raise', 'me', 'up', 'so', 'I', 'can', 'stand', 'on', 'mountains', 'You', 'raise', 'me', 'up', 'to', 'walk', 'on', 'stormy', 'seas', 'I', 'am', 'strong', 'when', 'I', 'am', 'on', 'your', 'shoulders', 'You', 'raise', 'me', 'up', 'to', 'more', 'than', 'I', 'can', 'be', 'You', 'raise', 'me', 'up', 'so', 'I', 'can', 'stand', 'on', 'mountains']
{'when': 4, 'i': 11, 'am': 6, 'down': 1, 'and': 4, 'oh': 1, 'my': 2, 'soul': 1, 'so': 4, 'weary': 1, 'troubles': 1, 'come': 2, 'heart': 1, 'burdened': 1, 'be': 3, 'then': 1, 'still': 1, 'wait': 1, 'here': 1, 'in': 1, 'the': 1, 'silence': 1, 'until': 1, 'you': 8, 'sit': 1, 'awhile': 1, 'with': 1, 'me': 8, 'raise': 7, 'up': 7, 'can': 5, 'stand': 3, 'on': 7, 'mountainis': 1, 'to': 4, 'walk': 2, 'stormy': 2, 'seas': 2, 'strong': 2, 'your': 2, 'shoulders': 2, 'more': 2, 'than': 2, 'mountains': 2}
Process finished with exit code 0
6. 例题2:将字典的键与值互换
6.1 题目
如下字典,将键和值对换,即键作为值,值作为建。
——d = {‘book’:[‘python’, ‘datascience’], ‘author’:‘laoqi’, ‘publisher’:‘phei’}
6.2 程序代码
'''
如下字典,将键和值对换,即键作为值,值作为建。
——d = {'book':['python', 'datascience'], 'author':'laoqi', 'publisher':'phei'}
'''
import collections.abc
d = {'book':['python', 'datascience'], 'author':'laoqi', 'publisher':'phei'}
d2 = {}
# for x,y in d.items():
# # 由于d中book的值为列表,列表不能作为字典的键,判断字典的值是否为不可迭代对象
# # (不可用)if isinstance(y,collections.abc.Iterable) == True:
# if isinstance(y, collections.abc.Hashable) == False:
# print(type(y))
# y = tuple(y)
# # d2.setdefault(y, x)
# d2[y] = x
# print(d2)
# 字典解析方式
d2 = {y if isinstance(y, collections.abc.Hashable) else tuple(y):x for x,y in d.items()}
print(d2)
6.3 运行结果
C:\Users\邢程\AppData\Local\Programs\Python\Python38\python.exe "D:/Python 项目/入门/1.3.3_for_example02.py"
{('python', 'datascience'): 'book', 'laoqi': 'author', 'phei': 'publisher'}
Process finished with exit code 0
涉及知识:
判断对象是否为不可迭代对象
可哈希的对象可理解为不可变对象
不可哈希的对象为可变对象
>>> d = [1,2]
>>> isinstance(d, collections.abc.Iterable)
True
>>> d= 1
>>> isinstance(d, collections.abc.Iterable)
False
>>> d = 'hello'
>>> isinstance(d, collections.abc.Iterable)
True
>>> d = tuple()
>>> isinstance(d, collections.abc.Iterable)
True
>>> d = dict()
>>> isinstance(d, collections.abc.Iterable)
True
>>>
>>> d= 1
>>> isinstance(d, collections.abc.Hashable)
True
>>> d = 'hello'
>>> isinstance(d, collections.abc.Hashable)
True
>>> d = tuple()
>>> isinstance(d, collections.abc.Hashable)
True
>>> d = dict()
>>> isinstance(d, collections.abc.Hashable)
False
>>>
>>> d = 1
>>>
>>> isinstance(d, collections.abc.Hashable)
True
>>> d = 'hello'
>>> isinstance(d, collections.abc.Hashable)
True
>>> d = [1, 2, 3]
>>> isinstance(d, collections.abc.Hashable)
False
>>> d = (1, 2, 3)
>>> type(d)
<class 'tuple'>
>>> isinstance(d, collections.abc.Hashable)
True
>>> dict = {1:"hello", 2:"python"}
>>> isinstance(d, collections.abc.Hashable)
True
>>>
7. 作业
7.1 题目
有字符串:Life is short You need python
——显示每个单词大写和小写两种状态
——统计每个单词的长度
7.2 程序代码
'''
有字符串:Life is short You need python
——显示每个单词大写和小写两种状态
——统计每个单词的长度
'''
str1 = 'Life is short You need python'
lst = str1.split()
print(lst)
for i in range(len(lst)):
print("单词为{0}".format(lst[i]))
print("大写状态为{0}".format(lst[i].upper()))
print("小写状态为{0}".format(lst[i].lower()))
print("长度为{0}".format(len(list(lst[i]))))
print("____________________________")
7.3 运行结果
C:\Users\邢程\AppData\Local\Programs\Python\Python38\python.exe "D:/Python 项目/入门/1.3.3_for_job.py"
['Life', 'is', 'short', 'You', 'need', 'python']
单词为Life
大写状态为LIFE
小写状态为life
长度为4
____________________________
单词为is
大写状态为IS
小写状态为is
长度为2
____________________________
单词为short
大写状态为SHORT
小写状态为short
长度为5
____________________________
单词为You
大写状态为YOU
小写状态为you
长度为3
____________________________
单词为need
大写状态为NEED
小写状态为need
长度为4
____________________________
单词为python
大写状态为PYTHON
小写状态为python
长度为6
____________________________
Process finished with exit code 0