笔记1.列表数据类型——列表使用

1.基本下标

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
    就像下标可以从列表中取得单个值一样,“切片”可以从列表中取得多个值,结果是一个新列表。切片输入在一对方括号中,像下标一样,但它有两个冒号分隔的整数。请注意下标和切片的不同。
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam[-1] = 12345
>>> spam
['cat',  'bat', 'rat', 12345]

笔记1:spam[-1]指的是从右往左第一个数;spam[0]指的是从左往右第一个数;spam[0:4]是指从左到右下标0-3个数,但不包含下标为4的数;spam[0:-1]是指从左下标0到右下标-2的数,但不包含下标为-1的数;可以使用列表的下标来改变下标处的值。

2.使用冒号

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']

笔记2:省略第一个下标相当于使用0,或列表的开始。省略第二个下标相当于使用列表的长度,意味着分片直至列表的末尾

3.不必使用多个重复的变量,你可以使用单个变量,包含一个列表值

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)

上面的输出类似会是这样的:

Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat-tail
Enter the name of cat 6 (Or enter nothing to stop.):
Miss Cleo
Enter the name of cat 7 (Or enter nothing to stop.):
The cat names are:
Zophie
Pooka
Simon
Lady Macbeth
Fat-tail
Miss Cleo

笔记3:使用列表的好处在于,现在数据放在一个结构中,所以程序能够更灵活的处理
数据,比放在一些重复的变量中方便。注意后面for name in catNames:
print(' ' + name)的应用。

4.循环:一个常见的Python 技巧,是在for 循环中使用range(len(someList)),迭代列表
的每一个下标。例如,在交互式环境中输入以下代码:

>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders

在前面的循环中使用range(len(supplies))很方便,这是因为,循环中的代码可以访问下标(通过变量i),以及下标处的值(通过supplies[i])。最妙的是,range(len(supplies))
将迭代supplies 的所有下标,无论它包含多少表项。

你可能感兴趣的:(笔记1.列表数据类型——列表使用)