python关于列表的操作

列表是Python中最基本的数据结构,列表是最常用的Python数据类型,列表的数据项不需要具有相同的类型。列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。序列都可以进行的操作包括索引,切片,加,乘,检查成员。此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法

1.创建一个列表:

list1=[1,5,9,"15","$%%","piao"];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

相比于java中的数组一样,列表也可以截取:

2.访问一个列表

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

输出结果:

list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]

3.更新列表

list = ['physics', 'chemistry', 1997, 2000];
print list[2];
list[2] = 2001;
print list[2];

输出结果:

1997

2001

4.删除列表元素

ist1 = ['physics', 'chemistry', 1997, 2000];

print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;

 输出的结果是:

['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

5.列表的循环输出

for i in range(len(list1)):
    print list1[i];

length=len(list1);(计算速度较快的,因为只用计算一次list的长度)
for i in range(length):
    print list[i];

i=0;(计算速度较快的,因为只用计算一次list的长度)
length=len(list1);
while i<length:
    print list[i];
    i+=1;

i=0;
while i<len(list1):
     print list[i];
    i+=1;

总结:1.list中的元素类型不固定:

         2.list中的元素值可变;

         3.list是按顺序(索引)排列的。

原文地址:https://www.cnblogs.com/mlmy/p/6298582.html