Python学习之列表(1)

为什么需要列表?

列表相当于一个容器。可以把一系列相关的值放在这个容器中进行存储。比如现在要存储水果的种类,那么如果通过之前的方式,一种水果用一个变量存储,那么代码将变得非常糟糕。正确的存储方式应该是定义一个列表类型的变量,然后把所有这些水果的名字存储到这个列表中。

###如何定义列表:使用左右两个中括号的形式 列表在其他编程语言中相当于数组

# fruits = ['apple','banana','orange']
#
# apple = fruits [0]
# banana = fruits [1]
# orange = fruits [2]
#
# print(apple)
# print(banana)
# print(orange)

##遍历列表
##1.for循环版本的遍历

# fruits = ['apple','banana','orange']
# print (type(fruits))
# for fruit in fruits:
# print(fruit)

##2.while循环版本的遍历
# index = 0
# fruits = ['apple','banana','orange']
# length =len(fruits )
# while index< length:
# fruit = fruits [index]
# index += 1
# print(fruit)

##列表嵌套(相当于其他编程语言中的多位数组):列表中可以存储任何数据类型,
# 当然也包括列表自身类型。即:列表中也可以存储列表:
# test_list = [1,2,3,['a','b','c']]
# for temp in test_list :
# # print(temp)
# if type(temp)== list:
# for temp_ in temp :
# print(temp_ )
# else:
# print(temp )

##列表相加:
# a = [1,2,3]
# b = [3,4,5]
# c = a + b
# print(c)


##列表的切片操作:1.开始位置:包括开始位置
# 2.结束位置:会取到结束位置前一个元素
#3.步长:默认为1,如果步长为负数,则从右到左,如果步长为整数则从左到右
# a = [1,2,3,4,5,6,7,8,9]
# # # temp = a [0:6]
# # # temp = a [:] #取全部值
# # temp = a[0::2] #取奇数
# temp = a[-1::-1]
# print(temp )

###开始位置和结束位置其实也可以为负数,只不过如果是负数,那么最后一个元素是-1,以此类推

##列表的赋值
# greet = ['hello','world']
# greet[1] ='lucy'
# print(greet)

 

猜你喜欢

转载自www.cnblogs.com/godblessmehaha/p/11094815.html