在我看来python中的列表和C语言中的数组有着相似之处,但相较于C语言中的数组又有着很大的不同。在python中列表中的元素用起来要比C语言中的数组便利很多。(因为是初步学习所以对于列表的所有应用还不能完全了解,但后面会继续跟进)
在C和 C++语言中数都是从零算起,当然了python中也不例外也是从零算起。
例如下面这个代码:
number=['1','2','3','4']
print(number[0])
运行结果:
python中的列表不仅可以正着索引还可以倒着索引,只不过是要从-1开始
例如:names=['lihua','liu','lin','zhang'] print(names[-1])
运行结果:
如果想输出“lihua"写print(names[-4])也可以。
在python中修改列表也很简单,只需要直接对你想修改的直接修改便可。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
运行结果:
使用append将元素添加到列表末尾
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
运算结果:
使用方法insert() 可在列表的任何位置添加新元素。
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(1, 'ducati')
print(motorcycles)
因为从零算起所以输出结果为:
python中删除元素可以使用三种方法:
1、使用del方法,此方法要知道删除元素所处位置。例如:
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
2、使用pop方法。
使用pop()可以直接删除列表末尾的元素,而且可以再使用删去的值
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()#pop()可以删除末尾的元素
print(motorcycles)
print(popped_motorcycle)#依然能访问被删除的值
除此之外pop()还可以对指定位置的列表元素进行删除,删掉的元素还可以再应用
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(1)#每当你使用pop() 时,被弹出的元素就不再在列表中了。
print(motorcycles)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
运行结果:
注释:如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del 语句;如果你要在删除元 素后还能继续使用它,就使用方法pop()。
3、如果不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
使用sort对列表永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)#汽车是按字母顺序排列的,再也无法恢复到原来的排列顺序
reverse=True 可以按字母逆序排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)#按字母逆序排列
print(cars)#同样,对列表元素排列顺序的修改是永久性
使用函数使用函数sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("Here is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)#调用函数sorted() 后,列表元素的排列顺序并没有变
运行结果:
同样sorted也可以按字母逆序排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
print(sorted(cars, reverse=True))
print(cars)
运行结果:
倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
运行结果:
确定列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
x=len(cars)#也可以print(len(cars))
print(x)
运行结果:
这便是对列表的初步学习,后面会继续跟进。