python list和tuple

list列表

简述:
  1. list是一种有序的集合,列表中的每个元素都分配一个数字 - 索引。

  2. 列表的元素不需要具有相同的类型,可以随时添加和删除其中的元素

  3. 创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可 。

    list1 = [1, 2, 3]
    list2 = ['a', 'b', 'c']
    list3 = [1, 2, 3, 'a', 'b', 'c']

遍历list

for循环:
name_list = ['Tom', 'Jake', 'Jim']

for name in name_list:
    print(name)

for i, name in enumerate(name_list):
    print(i, name)
while循环:
name_list = ['Tom', 'Jake', 'Jim']

i = 0
length = len(name_list)
while i < length:
    print(name_list[i])
    i += 1

列表相关操作

  1. 添加元素 (append,extend,insert)
    
    # append可以向列表添加元素
    
    list1 = ['a', 'b', 'c']
    list1.append('d')
    print(list1)  # ['a', 'b', 'c', 'd']
    
    
    # extend可以将另一个集合中的元素逐一添加到列表中
    
    list2 = [1, 2, 3]
    list2.extend(list1)
    print(list2)  # [1, 2, 3, 'a', 'b', 'c', 'd']
    
    
    # insert在指定位置index前插入元素
    
    list3 = ['q', 'w', 'e', 'r']
    list3.insert(1, 'A')
    print(list3)  # ['q', 'A', 'w', 'e', 'r']
  2. 删除元素 (del,pop,remote)
    
    # del根据下标进行删除
    
    list1 = [1, 2, 3, 4]
    del list1[0]
    print(list1)  # [2, 3, 4]
    
    
    # pop删除最后一个元素,并返回被删除元素,可设置指定下标
    
    list2 = ['a', 'b', 'c', 'd']
    temp = list2.pop()
    print(temp)  # b
    print(list2)  # ['a', 'c', 'd']
    
    
    # remove根据元素的值进行删除
    
    list3 = ['A', 'B', 'C', 'D']
    list3.remove('A')
    print(list3)  # ['B', 'C', 'D']
  3. 修改元素
    
    # 修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改
    
    list1 = [1, 2, 3, 4]
    list1[1] = 'A'
    print(list1)  # [1, 'A', 3, 4]
  4. 查找元素 (in,not in,index,count)
    
    # in(存在),如果存在那么结果为true,否则为false
    
    
    # not in(不存在),如果不存在那么结果为true,否则false
    
    list1 = ['a', 'b', 'c', 'd']
    print('a' in list1)  # True
    print('A' in list1)  # False
    
    
    # index和count与字符串中的用法相同
    
    list2 = ['1', '2', '3', '4', '1']
    print(list2.count('1'))  # 2
    print(list2.index('1', 0, len(list2)))
  5. 排序 (sort,reverse)
    
    # sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
    
    list1 = [1, 4, 7, 9, 2, 3]
    list1.sort()
    print(list1)  # [1, 2, 3, 4, 7, 9]
    
    
    # reverse方法是将list逆置。
    
    list2 = [1, 4, 7, 9, 2, 3]
    list2.reverse()
    print(list2)  # [3, 2, 9, 7, 4, 1]
  6. 复制list
    list1 = [1, 2, 3, 4]
    list2 = list1.copy()
    list3 = list(list1)
    
    print(list1, id(list1))  # [1, 2, 3, 4] 165084360
    print(list2, id(list2))  # [1, 2, 3, 4] 165081224
    print(list3, id(list3))  # [1, 2, 3, 4] 41551816

tuple元组

简介:
  1. tuple和list非常类似,但是tuple一旦初始化就不能修改 。
  2. 元组使用小括号,列表使用方括号

    tuple1 = ()
    tuple2 = tuple()
    tuple3 = ('a',)
    tuple4 = (1, 2, 3, 4)

案例

一个学校,有3个办公室,现在有8位老师等待工位的分配,请编写程序,完成随机的分配

import random

offices = [[], [], []]
names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
for name in names:
    index = random.randint(0, 2)
    offices[index].append(name)
print(offices)  # [['a', 'b', 'd', 'e', 'f', 'g'], ['c', 'h'], []]

猜你喜欢

转载自blog.csdn.net/qq_14876133/article/details/80929652