前情回顾:基本的数据表达方式为:int(),str(),float(). 其中int为数字,float为小数,string为字符串。
现在开始
那么在实战程序中,你可以用什么方法存储数据呢?
列表
列表是第一种方法,对于我来说也是最简单的。生成一个列表很简单,具体代码:
x=[]
我们可以针对这个列表做出一些修改。
语句1:append
append语句的用处就是将一个元素加入列表中。
x=[]
x.append(1)
print(x)
x中就有一个元素了,一个列表中可以有很多个元素,而列表中也可以又列表 ,套娃嘛,呵呵。
x=[]
listx=[1,20]
for i in range(100):
x.append(listx)
print(x)
>>> print(x)
[[1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20], [1, 20]]
>>>
对于列表,除了追加东西,你还可以替换列表中的数据类型,可以将他们转化成另一种数据类型。
x=str(input("Input a number you want"))
listx=[]
for i in range(100):
listx.append(x)
y=list(map(int,listx))
print(y)
在中间,运用的语句时list(map(type, list)),老方法会比这个笨拙。
索引
列表中重要的是索引,索引是在列表后面加一个中括号,中间填上索引的第几个元素(数字).但是索引永远是从零开始,到列表长度-1.如果超过就会反应错误:list index out of range.
listx=[1,2,3,4,5]
print(listx[0])#返回值是1
列表还有很多语句包括replace, del.
Replace用法.
listx=[1,2,3,4,5]
listx[0:4]=[2,3,4,5,6]
print(listx)#返回值为[2,3,4,5,6]
中括号之间的范围是你选择开始的索引值,和选择最后的索引值。同理也可以是1-4,2-4,3-4,1-3,1-2等等.
Delete 用法
listx=[1,2,3,4,5]
del listx[2]
print(listx)#返回值变成[1,2,4,5]
使用del语句删除的是索引对应的值。
remove 用法
listx=[1,2,3,4,5]
listx.remove(3)
print(listx)#返回值变成:[1,2,4,5]
使用remove语句删除的是首个符合输入的元素。
Index
我们在创建了一个列表之后可以通过这个列表调用一个函数叫做index,通过index可以访问一些索引。比如说一个元素所在的索引,这个列表中最小的元素等等。
listx=[1,2,3,4,5]
print(listx.index(max(listx)))
print(listx.index(min(listx)))
通过index我们定位到了最大值和最小值的索引。
同样也可以找到任何元素的索引。
listx=[1,2,3,4,5]
print(listx.index(5))
print(listx.index(4))
返回值依次是4,3
sort()
sort语句很简单,讲索引从小到大排列.
listx=[2,4,3,1,3,4,5,5,4,6,7,9,7,4,6,4]
listx.sort()
print(listx)
访问最大的值也可以用
listx[-1]
好的,那么关于列表的一些内容就讲完了,我在编程中也很喜欢运用列表,喜欢我的话可以在b站关注我,Glimphello.
毕竟暑假那么难得,做一些有意义的事不香嘛(¬_¬ )