列表
列表就像java里的collection,所具有的特性也要比元组更多,更灵活,其character总结如下:
-
任意对象的有序集合;
-
可通过偏移存取,注意,列表中的元素都是可变的,这是不同于元组的;
-
长度可变,支持嵌套;
-
还有一些类似java的对象引用机制
由于列表的这些特性,使得列表在实际应用中被广泛使用,下面是一些例子。
-
#coding:utf-8
-
#!/usr/bin/python
-
# Filename: list.py
-
-
fruit = ["banana", "apple", "quince"]
-
-
#增,删,改,查
-
-
fruit[1:1]=["pear"] #只有这种情况才是插入
-
fruit.append("appendtodog")
-
print fruit
-
-
#插入1到2变成pear
-
fruit[1:3]=["pear"]
-
print fruit
-
#删除最后一个元素
-
del fruit[-1]
-
print fruit
-
#修改
-
fruit[-1]="king"
-
print fruit
-
#查询
-
if "banana" in fruit:
-
print "banana is exist"
-
-
-
fruit2 = ["banana", "apple", "quince","orange","tomato","pear"]
-
for i in xrange(len(fruit2)):
-
print fruit2[i],
-
-
print "n",
-
fruit3 = fruit2[0:3]
-
for str in fruit3:
-
print str,
-
-
#产生一个数值递增列表
-
num_inc_list = range(30)
-
print num_inc_list
-
-
initial_value=0
-
list_length = 5
-
#用某个固定值初始化列表
-
sample_list = [ initial_value for i in range(10)]
-
print sample_list
-
#用某个固定值初始化列表2,初始值加长度
-
sample_list2 =[initial_value]*list_length
-
print sample_list2
-
-
-
['banana', 'pear', 'apple', 'quince', 'appendtodog']
-
['banana', 'pear', 'quince', 'appendtodog']
-
['banana', 'pear', 'quince']
-
['banana', 'pear', 'king']
-
banana is exist
-
banana apple quince orange tomato pear
-
banana apple quince [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
-
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-
[0, 0, 0, 0, 0]
阅读(16253) | 评论(0) | 转发(1) |