列表1-python基础篇四

  列表列由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有 任何关系。鉴于列表通常包含多个元素,给列表指定一个表示复数的名称(如letters 、digits 或names )是个不错的主意。

  在Python中,用方括号([] )来表示列表,并用逗号来分隔其中的元素。下面是一个简单的列表示例,这个列表包含几种自行车:
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

#结果:['trek', 'cannondale', 'redline', 'specialized']

访问列表元素

  列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。在Python中,第一个列表元素的索引为0,而不是1。

  例如,下面的代码从列表bicycles 中提取第一款自行车:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0])
#结果:trek
#如果想要更加干净
print(bicycles[0].title())
  Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1 ,可让Python返回最后一个列表元素:
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles[-1])

  切片练习

list1 = ['牛奶', '面包', '火腿肠', '辣条', '臭豆腐', '食盐', '方便面']
#  通过索引获取列表里面的元素
print(list1[3])  # 辣条
print(list1[0])  # 牛奶
print(list1[:2])  # ['牛奶', '面包']
print(list1[::-3])  # ['方便面', '辣条', '牛奶']  -3是步长
print(list1[-2:-5:-2])  # ['食盐', '辣条']
print(list1[-2::-2])  # ['食盐', '辣条', '面包']
print(list1[::3])  # ['牛奶', '辣条', '方便面']
print(list1[-2::-5])  # ['食盐', '牛奶']
print(list1[::-1])  # ['方便面', '食盐', '臭豆腐', '辣条', '火腿肠', '面包', '牛奶']

 

修改、添加和删除元素

  1、修改

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) 
motorcycles[0] = 'ducati'  #修改第一个元素后输出
print(motorcycles)

#结果1:['honda', 'yamaha', 'suzuki']
#结果2:['ducati', 'yamaha', 'suzuki']

   2、添加

  (1)在表末尾添加值,方法append() 将元素添加到了列表末尾,也可以使用append动态的创建表。

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

#结果1:['honda', 'yamaha', 'suzuki'] 
#结果2:['honda', 'yamaha', 'suzuki', 'ducati']

motorcycles = []
#使用append让动态地创建列表
motorcycles.append('honda') 
motorcycles.append('yamaha')
motorcycles.append('suzuki')

print(motorcycles)
#结果:['honda', 'yamaha', 'suzuki']

  列表拼接

'''
数字:n=1+3
字符串:s='aa'+'bb'
列表:list0 =[1,2,3]+['a'+'b']----->[1,2,3,'a','b']
'''
list1 = ['薯条', '汉堡', '牛奶']
list2 = ['油条', '肉包', '豆浆']
list3 = list1 + list2
list4 = list1.extend(list2)
print(list3)  # ['薯条', '汉堡', '牛奶', '油条', '肉包', '豆浆']
print(list4)  # None
print(list1)  # ['薯条', '汉堡', '牛奶', '油条', '肉包', '豆浆']

  列表的嵌套,购物车实例:

'''
买多件
商品名称,价格,数量
要用到列表的嵌套
'''
container = []  # 存多件商品的容器
flag = True
while flag:
    name = input('名称')
    price = input('价格')
    number = input('数量')
    goods = [name, price, number]  # 形成一个商品列表
    container.append(goods)  # 列表嵌套,把一个商品列表放入另一个列表
    # 当输入‘q’时,停止输入
    q = input("是否继续购物,按q退出")
    if q.lower() == 'q':
        flag = False
print('*-' * 20)
#  遍历购物车
print('商品\t价格\t数量')
print('{}{}{}'.format('商品'.center(10), '价格'.center(10), '数量'.center(10)))
for goods in container:
    #  print('{}\t{}\t{}'.format(goods[0], float(goods[1]), int(goods[2])))
    #  10个字符居中对齐
    print('{}{}{}'.format(goods[0].center(10), goods[1].center(12), goods[2].center(12)))

  (2)在列表中插入元素。使用方法insert() 可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值。

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)

#输出结果:['ducati', 'honda', 'yamaha', 'suzuki']

  3、从列表中删除元素

  (1)使用使 del 语句删除元素,可以通过索引来删除任意一个元素。

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
#输出结果1:['honda', 'yamaha', 'suzuki']
#输出结果1:[ 'yamaha', 'suzuki']

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[1]
print(motorcycles)
#输出结果1:['honda', 'yamaha', 'suzuki']
#输出结果1:['honda', 'suzuki']

  del()如给不给任何参数,会删除整个列表,因为列表不存在了如果再次使用会报错。  

(2)使用方法 使 pop() 删除元素,方法pop() 可删除列表末尾的元素,并让你能够接着使用它。

motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")
#输出结果:The last motorcycle I owned was a Suzuki.
    pop() 也可以删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')

  (3)根据值删除元素。只知道要删除的元素的值,而不知道索引,可使用方法remove() 。并且使用remove() 从列表中删除元素时,也可接着使用它的值。remove() 只删除第一个同名的值,如果后面还要其他相同的值是不删除的

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

#结果1:['honda', 'yamaha', 'suzuki', 'ducati']
#结果2:['honda', 'yamaha', 'suzuki']

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive) print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.")

'''
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.
'''

   remove()删除可能出现值不存在的情况,这个时候回报错:ValueError: list.remove(x): x not in list,因此需要加个判断有没有这个值:

list1 = ['面包', '辣条', '辣条', '饼干', '果冻', '辣条']
# list1.remove('辣条a')
if '辣条a' in list1:
    list1.remove('辣条a')
else:
    print("不存在'辣条a'")
print(list1)  # ['面包', '辣条', '饼干', '果冻', '辣条']

  remove()循环删除相同的值

#  循环删除多个相同的值辣条
for i in list1:  # 这里for循环存在一个漏洞,如果有相同的两个值这相邻的位置会漏删一个
    if i == '辣条':
        list1.remove(i)
print(list1)  # ['面包', '饼干', '果冻', '辣条']
# 上面的结果还是有一个辣条,原因是列表的下标发生了变化,后面的下标都向前进了一位
print('*-' * 20)
list2 = ['面包', '辣条', '辣条', '饼干', '果冻', '辣条']
n = 0
while n < len(list2):
    if list2[n] == '辣条':
        list2.remove('辣条')
    else:
        n += 1  # 阻止下标都向前进了一位
print(list2)  # ['面包', '饼干', '果冻'],没有了辣条

print('*-' * 20)
list3 = ['面包', '辣条', '辣条', '饼干', '果冻', '辣条']
#  for循环倒着循环,可以删除多个相同的值辣条
for i in list3[::-1]:  # 倒着循环
    if i == '辣条':
        list3.remove(i)
print(list3)  # ['面包', '饼干', '果冻']

   clear()不传任何参数,直接清空列表。

列表查找方法归纳

  1、元素 in 列表 :元素是否在列表中。 元素 not in 列表:元素是否不在列表中。 /返回bool

  2、列表.index(元素) :返回元素的下标位置,如果没有此元素则报错。

  3、列表.count(元素) :返回整数,返回0则标识不存在此元素,返回整数表示此元素的个数。

组织列表排序

  1、使用方法 使 sort() 对列表进行永久性排序。方法sort()永久性地按字母顺序修改了列表元素的排列顺序,使用参数“reverse=True”可以按与字母顺序相反的顺序排列。

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
#['audi', 'bmw', 'subaru', 'toyota']

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
#['toyota', 'subaru', 'bmw', 'audi']

  2、使用函数使 sorted() 对列表进行临时排序。

cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

"""
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again: ['bmw', 'audi', 'toyota', 'subaru']
"""

  3、要反转列表元素的排列顺序,可使用方法reverse()

  4、确定列表的长度,使用函数len() 可快速获悉列表的长度。

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4

   5、冒泡排序。

 

nums = [5, 1, 7, 6, 8, 2, 4, 3]
for j in range(0, len(nums) - 1):
    for i in range(0, len(nums) - 1 - j):
        if nums[i] > nums[i + 1]:
            a = nums[i]
            nums[i] = nums[i + 1]
            nums[i + 1] = a
print(nums)

 

 

 

posted @ 2021-09-03 10:45  逍遥abin  阅读(96)  评论(0编辑  收藏  举报