the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
#this first kinf of for-loop goes through a list
for number in the_count:
print"this is count%d"%number
#same as above
for fruit in fruits:
print"a fruit of type:%s"%fruit
#also we can go through mixed lists too.
#notice we have to use %r since we don't know what's in it
for i in change:
print "i got %r."%i
'''#also we can build a list, first start with a empty one
elements=[]
#the use the range function to do 0 to 5 counts
for i in range(0,6):
print"adding %d to the list."%i
#append is a function that lists understand
elements.append(i)
#now we can print them out too
for i in elements:
print"element was: %d"%i'''
elements = range(0,6)
for i in elements:
print"element was%d"%i
- 学会创建list a = []
- for-loop :for i in xxx 从xxx依次提取出元素 赋值给 i
- range(x,y) 创建一个list 包含 x to y
- .append(x)在list末尾加入x
列表操作方法:
list.append(obj) 在列表的末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(*obj) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
list.insert(index,obj) 将对象插入列表,第一个参数可以是位置
list.pop(obj=list[-1] 移除列表中的一个元素(默认最后一个元素),并返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
liest.reverse() 反向列表中的元素
list.sort[func] 对原列表进行排序,参数reverse=True时,从大到小排序
list.clear() 清空这个列表(感觉毫无卵用....)
摘自 https://www.cnblogs.com/dyjn/p/5634323.html