一入python深似海--list

几个实例展示python中数据结构list的魅力!

list变量申明

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

访问list元素

array= [1,2,5,3,6,8,4]
#其实这里的顺序标识是
(0,1,2,3,4,5,6)
(-7,-6,-5,-4,-3,-2,-1)#有负的下标哦
 
array[0:]#列出index==0以后的
[1,2,5,3,6,8,4]
array[1:]#列出index==1以后的
[2,5,3,6,8,4]
array[:-1]#列出index==-1之前的
[1,2,5,3,6,8]
array[3:-3]#列出index==3到index==-3之间的,<span style="color:#ff0000;">注意不包含index==-3,即左闭右开</span>
[3]

list应用

loops and list

change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
for i in change:
    print "I got %r" % i

enumerate

for i,j in enumerate([[1,2],['o',2],[9,3]]):
	k1,k2=j
	print i,k1,k2

output
0 1 2
1 o 2
2 9 3


append/extend/pop/del

append()添加元素至list尾部
elements=[1,2,3,4,5]
elements.append(6)

extend()拼接两个list
list1=[1,2,3,4,5]
list2=[6,7]
elements.extend(list2)
print elements

pop(int i=-1)删除list中指定下标的元素,并返回该位置上的数,default :删除最后一个
elements=[1,2,3,4,5]
print elements.pop()#default:delete index==-1,i.e. the last element
print elements
elements=[1,2,3,4,5]
elements.pop(-2)#delete index==-2,i.e. 4
print elements
elements.pop(1)
print elements

del
elements=[1,2,3,4,5]
del elements[0]#default:delete index==0,i.e. 1
print elements
elements=[1,2,3,4,5]
del elements[2:4]#delete index==2 and index==3,i.e.3 and 4
print elements
elements=[1,2,3,4,5]
del elements#delete all
elements

do things to list

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print "Wait there's not 10 things in that list, let's fix that."

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print "Adding: ", next_one
    stuff.append(next_one)
    print "There's %d items now." % len(stuff)

print "There we go: ", stuff

print "Let's do some things with stuff."

print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar! outputs:stuff[3]#stuff[4]


‘ ‘.join(things) reads as, "Join things with ‘ ‘ between them." Meanwhile, join(‘ ‘, things) means, "Call join with ‘ ‘ and things。返回一个string.
输出
Wait there's not 10 things in that list, let's fix that.
Adding:  Boy
There's 7 items now.
Adding:  Girl
There's 8 items now.
Adding:  Banana
There's 9 items now.
Adding:  Corn
There's 10 items now.
There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Banana
['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Corn']
Apples Oranges Crows Telephone Light Sugar Boy Girl Corn
Telephone#Light#Sugar



一入python深似海--list,布布扣,bubuko.com

一入python深似海--list

上一篇:Android中的ContentValues用法


下一篇:iOS学习笔记---oc语言第六天