1.遍历整个列表
>>>name=['a','b','c']
>>>for name1 in name:
>>> print(name1)
a
b
c
2.避免缩进错误
name=['a','b','c']
for name2 in name:
print(name1)
------------------
File "name.py",line3
print(name1)
^
IndentationError:expected an indented block
-------------------------------------------
name ="this is a string"
print(name)
------------------------
File "name.py",line2
print(name)
^
IndentationError:unexpected indent
----------------------------------
name=['a','b','c']
for name1 in name:
print(f"{name1}\n")
print("end")
-----------------------
a
end
b
end
c
en
----
遗漏了冒号:for语句末尾的冒号是为了说明,下面是循环的第一行。
3.创建数值列表
>>>for value in range(1,5):
>>> print(value)
1
2
3
4
#range(6)返回数0~5
>>>name=list(range(1,6))
>>>print(name)
[1,2,3,4,5]
>>>name=list(range(2,11,2))
>>>print(name)
[2,4,6,8,10]
#**表示乘方
>>>2**2
4
4.对数字列表进行简单的统计计算
>>>name=[1,2,3,4,5]
>>>min(name)
1
>>>max(name)
5
>>>sum(name)
15
#列表解析
>>>name1=[name**2 for name in range(1,4)]
>>>print(name1)
[1,4,9]
5.使用列表的一部分
切片
>>>name=['a','b','c']
>>>print(name[:1])
['a']
>>>print(name[0:2])
['a','b']
>>>print(name[-2:])
['b','c']
>>>for name1 in name[:2]:
>>> print(name)
a
b
#复制列表
>>>name2=name[:]
#name3和name的关系是别名
>>>name3=name
6.元组
#不可变的列表被称为元组
#元组,使用圆括号而不是方括号
>>>name=(200,50)
>>>print(name[0])
200
>>>name[0]=20
----------------------------
Traceback(most recent call last):
File "name.py",line1,in<module>#模块
name[0]=20
TypeError:'tupe' object does not support item assignment
--------------------------------------------------------
#元组是由,组成的
>>>name=(3,)
----------------
#修改元组变量
>>>name=(0,2)
>>>name=(1,2)
详见《python编程从入门到实践》