一入python深似海--list,,几个实例展示pyth
一入python深似海--list,,几个实例展示pyth
几个实例展示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=jprint i,k1,k2
output
0 1 21 o 22 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 elementprint elementselements=[1,2,3,4,5]elements.pop(-2)#delete index==-2,i.e. 4print elementselements.pop(1)print elements
del
elements=[1,2,3,4,5]del elements[0]#default:delete index==0,i.e. 1print elementselements=[1,2,3,4,5]del elements[2:4]#delete index==2 and index==3,i.e.3 and 4print elementselements=[1,2,3,4,5]del elements#delete allelements
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: ", stuffprint "Let's do some things with stuff."print stuff[1]print stuff[-1] # whoa! fancyprint 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: BoyThere's 7 items now.Adding: GirlThere's 8 items now.Adding: BananaThere's 9 items now.Adding: CornThere's 10 items now.There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']Let's do some things with stuff.OrangesCornBanana['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Corn']Apples Oranges Crows Telephone Light Sugar Boy Girl CornTelephone#Light#Sugar
一入python深似海--list,布布扣,bubuko.com
一入python深似海--list
评论关闭