分类: Python/Ruby
2012-12-27 10:21:26
六、向数组中添加内容append
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist: # 遍历数组使用的是 for item in shoplist
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
"""
想数组中添加内容使用的是:append
"""
七、使用sort分组数组
shoplist = ['apple', 'mango', 'carrot', 'banana']
shoplist.sort()
print 'Sorted shopping list is', shoplist
Sorted shopping list is ['apple', 'banana', 'carrot', 'chen', 'mango'] #分组之后的数组。
分组是按照首字母来分组的。
八、删除数组成员
shoplist = ['apple', 'mango', 'carrot', 'banana']
olditem = shoplist[0]
del shoplist[0] #使用del来实现对数组的第一个成员进行删除
print 'I bought the', olditem
print 'My shopping list is now', shoplist
九、求数组的长度
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
十、for循环
shoplist=['apple','banana','chen','chenlei','wuxi']
print 'shoplist num is :',len(shoplist)
shoplist.append('bad')
for item in shoplist:
print item, #注意这里加上了一个“ , ”号,要是不加上的话就会每输出一个就自动换行
--------------------------------
结果 :
shoplist num is : 5
apple banana chen chenlei wuxi bad