for语句
for语句可以为一个集合(序列和其他可迭代对象)的每个元素都执行一个代码块
字符串、元组、列表、字典都属于可迭代对象
如果能用for循环,尽量不用while循环
a = "python"
for i in a:
print(i)
p
y
t
h
o
n
a = "python"
for i in range(len(a)):
print(a[i])
p
y
t
h
o
n
#循环列表
for i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
#循环列表
names = ['newton', 'einstein', 'hertz', 'maxwell', 'bohr']
for name in names:
print(name, end="--*--")
newton--*--einstein--*--hertz--*--maxwell--*--bohr--*--
#循环字典,得到key
d = dict([("name", "laoqi"), ("lang", "python"), ("age", 38), ("city", "soochow")])
for k in d:
print(k)
name
lang
age
city
#循环字典,得到键-值对
for k in d:
print(k, "-->", d[k])
name --> laoqi
lang --> python
age --> 38
city --> soochow
#利用items,字典items()方法以列表返回可遍历的(键, 值) 元组数组。
for k, v in d.items():
print(k, "-->", v)
name --> laoqi
lang --> python
age --> 38
city --> soochow
#1234不是可迭代对象
for n in 1234:
print(n)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-bee958533cac> in <module>
----> 1 for n in 1234:
2 print(n)
TypeError: 'int' object is not iterable
#调出列表lst中含有“a”的字符串,创建新的列表new
lst = ["anwang", 'ibm', "compaq", "lenovo", "dell"]
new = []
for n in lst:
if "a" in n:
new.append(n)
print(new)
['anwang', 'compaq']
#循环计数字典
t = (3, 6, 1, 0, 2, 4, 9, 6, 3, 4, 9, 7, 1, 3, 5)
d = {}
for n in t:
if n in d:
d[n] += 1
else:
d[n] = 1
print(d)
{3: 3, 6: 2, 1: 2, 0: 1, 2: 1, 4: 2, 9: 2, 7: 1, 5: 1}
range函数
#获取0到100,能被3整除的数
for i in range(100):
if i%3 == 0:
print(i)
0
3
6
9
12
15
18
21
24
27
30
33
36
39
42
45
48
51
54
57
60
63
66
69
72
75
78
81
84
87
90
93
96
99
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.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __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, [start, [stop]]) -> integer -- return index of value.
| Raise ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| start
|
| step
|
| stop
#获取0到100,能被3整除的数
list(range(0,100,3))
[0,
3,
6,
9,
12,
15,
18,
21,
24,
27,
30,
33,
36,
39,
42,
45,
48,
51,
54,
57,
60,
63,
66,
69,
72,
75,
78,
81,
84,
87,
90,
93,
96,
99]
#対应元素相加,形成新列表
a = [1,2,3,4]
b = [9,8,7,6]
c = []
for i in range(len(a)):
c.append(a[i]+b[i])
c
[10, 10, 10, 10]
zip函数
将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
m = "laoqi"
n = "python"
zip(m,n)
<zip at 0x15561a35248>
list(zip(m,n))#对应元素打包成元组
[('l', 'p'), ('a', 'y'), ('o', 't'), ('q', 'h'), ('i', 'o')]
#対应元素相加,形成新列表
a = [1,2,3,4]
b = [9,8,7,6]
d = []
for x,y in zip(a,b):
d.append(x+y)
d
[10, 10, 10, 10]
enumerate()遍历元素
#创建有20个随机数的列表
lst = []
import random
for i in range(20):
lst.append(random.randint(1,100))
print(lst)
#查找所有的偶数,并用“even”作为标签代替
for n in lst:
if n % 2 == 0:
idx = lst.index(n)
lst[idx] = "even"
print(lst)
print("-"*75)
#利用enumerate函数
lst2 = []
for i in range(20):
lst2.append(random.randint(1,100))
print(lst2)
for i,n in enumerate(lst2):
if n%2 == 0:
lst2[i] = "even"
print(lst)
[38, 72, 44, 58, 49, 3, 57, 37, 11, 38, 29, 87, 100, 82, 18, 57, 22, 49, 5, 31]
['even', 'even', 'even', 'even', 49, 3, 57, 37, 11, 'even', 29, 87, 'even', 'even', 'even', 57, 'even', 49, 5, 31]
---------------------------------------------------------------------------
[50, 49, 26, 25, 63, 30, 59, 78, 63, 82, 54, 98, 99, 75, 41, 39, 73, 70, 7, 99]
['even', 'even', 'even', 'even', 49, 3, 57, 37, 11, 'even', 29, 87, 'even', 'even', 'even', 57, 'even', 49, 5, 31]
s = ["a", "b", "b"]
print(list(enumerate(s)))
#将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,
#一般用在 for 循环当中
print(list(enumerate(s,1)))#下标从1开始
[(0, 'a'), (1, 'b'), (2, 'b')]
[(1, 'a'), (2, 'b'), (3, 'b')]
dir(enumerate)
['__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__lt__',
'__ne__',
'__new__',
'__next__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__']