- import sys
- def listTest():
- # Python中的list类似数组,中文叫做列表
- colors = ["red", "blue", "green"]
- print(colors[1])
- # 声明一个引用指向同一列表
- newColors = colors
- print(newColors[2])
- # for...in遍历
- print("All colors in the mylist as follow: ")
- for color in colors:
- print(" " + color)
- # in测试成员资格
- print("测试成员资格in:" + str("red" in colors)) # True
- print("测试成员资格in:" + str("yellow" in colors)) # False
- # range,range(a, b)得到一个列表:a,a+1,a+2...b-1
- # 产生0-99
- numbers = range(0, 100)
- print("Numbers from 0 to 99: ")
- for number in numbers:
- print(" " + str(number))
- # while loop
- i = 0;
- while i < len(colors):
- print(colors[i])
- i += 1
- # list的方法
- mylist = ['a', 'b', 'c']
- # append(),在列表末尾追加一个元素,会修改列表
- mylist.append('d')
- print(mylist)
- #insert(index, element),在指定索引位置插入新元素,会修改列表
- mylist.insert(1, 'e')
- print(mylist)
- # extend()进行列表扩展,会修改列表
- mylist.extend(['f', 'g'])
- print(mylist)
- # += 也可以扩展列表,我猜这种方式可能会新建一个列表复制原列表元素和扩展的列表中的元素,然后返回
- mylist += ["h"]
- print(mylist)
- # list.index(elem),返回elem在列表中的索引,如果没找到抛出ValueError
- print("list index: the index of a in mylist is " + str(mylist.index("c")))
- # mylist.index("z") # ValueError: 'z' is not in list
- # list.remove(elem):如果元素不存在于列表,会抛出ValueError
- mylist.remove("e")
- print(mylist)
- # mylist.remove("o") # ValueError: list.remove(x): x not in list
- # 栈方式操作列表:pop(),注意没有push()方法,push()的替代方法是append
- mylist.pop()
- print("列表pop操作,列表的元素会减少:" + str(mylist))
- # 列表切片(slice)
- slicelist = ["Orange", "Apple", "Banana", "Pear"]
- print("列表切片:" + str(slicelist[1:-1]))
- slicelist[0:2] = "荔枝" # 猜猜结果是啥?想想列表扩容(字符串也是列表)
- print("列表切片:" + str(slicelist))
- slicelist[0:1] = "菠萝"
- print("列表切片:" + str(slicelist))
- def main():
- listTest()
- if __name__ == "__main__":
- main()
- #该片段来自于http://www.codesnippet.cn/detail/160720134618.html
来源: http://www.codesnippet.cn/detail/160720134618.html