掌握for循环语句的结构
语句的结构
>>> 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
>>> d = {'name':'laoma','lang':'python','age':39}
>>> for k in d:
... print(k)
...
name
lang
age
>>> for k in d:
... print(k,d[k])
...
name laoma
lang python
age 39
>>> d.items()
dict_items([('name', 'laoma'), ('lang', 'python'), ('age', 39)])
>>> for k,v in d.items():
... print(k,v)
...
name laoma
lang python
age 39
查看是否为可迭代对象
>>> for i in 325:
... print(i)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> hasattr(d,'__iter__')
True
>>> hasattr(325,'__iter__')
False
>>> import collections
>>> isinstance(325,collections.Iterable)
__main__:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
False
>>> import collections.abc
>>> isinstance(325,collections.abc.Iterable)
False
相关函数,都是内置函数
range()
>>> a = range(10)
>>> a
range(0, 10)
>>> 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]
>>> for i in range(100)
File "<stdin>", line 1
for i in range(100)
^
SyntaxError: invalid syntax
>>> for i in range(100):
... if i% 2 ==0:
... print(i)
...
>>> 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]
zip() 对应关系
>>> a = [1,2,3,4]
>>> b = [5,6,7,8]
>>> z = zip(a,b)
>>> z
<zip object at 0x000001BE8ACF2A48>
>>> list(zip(a,b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> dict(a=1,b=2)
{'a': 1, 'b': 2}
>>> dict(zip(a,b))
{1: 5, 2: 6, 3: 7, 4: 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)]
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
掌握列表解析(list comperhension)的使用方法
-列表解析
>>> [x+y for x , y in zip(a,b)]
[6, 8, 10, 12]
-字典解析
>>> d = {'a':1,'b':2,'c':3}
>>> {v:k for k,v in d.items()}
{1: 'a', 2: 'b', 3: 'c'}
-集合解析
>>> alist = [1,2,3,50,89,26,30]
>>> {i for i in alist if i%2 == 1}
{89, 1, 3}
在程序中应用for循环语句
例题:统计如下字符串中每个单词的数量
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 mountains You rasie 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 rasise me up so I can stand on mountains You rase 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'
lst = song.split(' ')
d = {}
for word in lst:
word = word.lower()
if word in d:
d[word] += 1
else:
d[word] = 1
print(d)
-例题2如下字典,将键和值对换
d = {‘book’:[‘python’,’,datascience’],‘author’:‘laoma’,‘publisher’:‘phei’}
>>> import collections.abc
>>> a
[1, 2, 3, 4]
>>> isinstance(a,collections.abc.Hashable)
False
>>> isinstance('laoma',collections.abc.Hashable)
True
>>> for k ,v in d.items():
... if isinstance(v , collection.abc.Hashable):
... dd
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'collection' is not defined
>>>
>>> d = {'book':['python',',datascience'],'author':'laoma','publisher':'phei'}
>>> dd = {}
>>> for k ,v in d.items():
... if isinstance(v , collections.abc.Hashable):
... dd[v] = k
... else:
... dd[tuple(v)] = k
...
>>> dd
{('python', ',datascience'): 'book', 'laoma': 'author', 'phei': 'publisher'}
>>> {v if isinstance(v,collections.abc.Hashable) else tuple(v): k for k,v in d.items()}
{('python', ',datascience'): 'book', 'laoma': 'author', 'phei': 'publisher'}