python04
C:\Users\liuwe>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> for i in range(3):
... print(i)
... else:
... print("无异常")
...
0
1
2
无异常
>>> for i in range(3):
... print(i)
... if i==1:
... break
... else:
... print("无break")
...
0
1
>>> while 1:
... print(1)
... break
... else:
... print("无break")
...
1
>>> n=3
>>> while n>=1:
... print(n)
... n=n-1
... else:
... print("无break")
...
3
2
1
无break
列表,元组和字典:数据结构:存数据的方式
增
>>> b=[1]
>>> type(b)
<class 'list'>
>>> a=[]
>>> a.append(1)
>>> a
[1]
>>> a.append(2)
>>> a
[1, 2]
>>> a.append("a")
>>> a
[1, 2, 'a']
>>> a.insert(0,"s")
>>> a
['s', 1, 2, 'a']
>>> a.append(2,"x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)
>>> a.insert(2,"x")
>>> a
['s', 1, 'x', 2, 'a']
>>>
>>> a.insert(2,"x")
>>> a
['s', 1, 'x', 2, 'a']
>>> a.extend(["m","n","z"])
>>> a
['s', 1, 'x', 2, 'a', 'm', 'n', 'z']
>>>
删
>>> del a[0]
>>> a
[1, 'x', 2, 'a', 'm', 'n', 'z']
>>>
改
>>> a[0]="ssss"
>>> a
['ssss', 1, 'x', 2, 'a', 'm', 'n', 'z']
a.remove()
a.pop()
查
列表,元组,字符串都是序列,使用坐标取值
>>> a=[1,2,3]
>>> for i in a:
... print(i)
...
1
2
3
当需要通过坐标实现计算过程使用如下方法
>>> for i in range(len(a)):
... print(a[i])
...
1
2
3
>>>
a=list(range(1,11))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> s=list("abcdef")
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> s
['a', 'b', 'c', 'd', 'e', 'f']
>>> s[2]=1
>>> s
['a', 'b', 1, 'd', 'e', 'f']
>>> "".join(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 2: expected str instance, int found
>>> s[2]="1"
>>> "".join(s)
'ab1def'
>>>
练习
1.一个list包含了2个a字母,请打印a字母所在的坐标
思考:用哪种方式可以获取坐标?if
l=[1,2,3,'a','a',4]
for i in range(len(l)):
if l[i]=a"
print(i)
result.append(i)
print(result)
2.把两个a字母替换为“*”
l=[1,2,3,'a','a',4]
for i in range(len(l)):
if l[i]=a"
print(i)
result.append(i)
print(result)
for i in result:
l[i]="*":
print(l)
3.构造一个list,包含字母和数字的,把全部的数字删除掉
方法1:过滤思想
result=[]
l=[1,2,3,'a','b','c']
for i in l:
if not isinstance(i,(int,float,complex)):
result.append(i)
print(result)
方法2:原有方法基础上去改
result=[]
l=[1,2,3,'a','b','c']
for i in range(len(l)):
if isinstance(l[i],(int,float,complex)):
result.append(l[i])
for i in result:
l.remove(i)
print(l)
元组:元组的内容不能修改
a=(1,2)
for i in a : #基于值来进行遍历
print(i)
for i in range(len(a)): #基于坐标的方法进行遍历
print(a[i])