1、使用列表
把变量存储在列表中,减少操作
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)
str(len(catNames) + 1) #第一段的时候列表为空,新词,初始为‘(0+1=)1’
2、列表用于循环
>>> 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
在for 循环中使用range(len(someList)),迭代列表的每一个下标----与上面一点类似。
3、in和not in操作符
利用in 和not in 操作符,可以确定一个值否在列表中。像其他操作符一样,in和not in 用在表达式中,连接两个值:一个要在列表中查找的值,以及待查找的列表。这些表达式将求值为布尔值。
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
4、列表多重赋值技巧
变量的数目和列表的长度必须严格相等
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
5、增强的赋值操作
+=操作符也可以完成字符串和列表的连接
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']