Day 7 Python 语法之list

Day 7 Python 语法之list

增 - 添加元素

  • 列表.append(元素): 在指定列表的最后添加指定的元素,没有返回值,可理解为追加

    scores = [89, 45, 99, 65, 93, 81, 29, 88, 76, 59, 66]
    new_scores = []
    for i in scores:
        if i <  60:
            new_scores.append(i)#在新列表中将满足条件的元素重新追加到列表末尾
    print(new_scores)
    
  • 列表.insert(下标,元素):在指定位置下标前插入指定元素

    heroes = ["寒冰射手", "小跑", "维鲁斯", "金克斯", "小法", "卡牌", "蛇女"]
    heroes.insert(-1,"压缩")  #插入到蛇女前面
    heroes.insert(0,"石头人")  #插入到最开始
    print(heroes)
    

  • del 列表[下标] : 用del关键字删除列表指定下标的元素

    heroes =['石头人', '寒冰射手', '小跑', '维鲁斯', '金克斯', '小法', '卡牌', '压缩', '蛇女']
    del heroes[0]
    print(heroes)
    del heroes[-2]
    print(heroes
    
  • 列表.remove(元素): 删除列表中指定的元素,没有返回值None,删除不存在的元素会报错,多个元素,删除遇到的第一个

    heroes =['石头人', '寒冰射手', '小跑', '维鲁斯', '金克斯','维鲁斯', '小法', '卡牌', '维鲁斯','压缩', '蛇女']
    heroes.remove("小跑")
    heroes.remove("维鲁斯")
    print(heroes)
    
  • 列表.pop() : 取出列表中的最后一个元素,有返回值

  • 列表.pop(下标) : 取出列表中指定下标的元素,并返回

    heroes =['石头人', '寒冰射手', '小跑', '维鲁斯', '金克斯','维鲁斯', '小法', '卡牌', '维鲁斯','压缩', '蛇女']
    result1 = heroes.pop()
    print(heroes,result1)
    result2 = heroes.pop(0)
    print(heroes,result2)
    

修改列表

  • 列表[下标] = 新元素 : 将新元素赋值给列表中指定下标对应的元素

    heroes =['石头人', '寒冰射手', '小跑', '维鲁斯', '金克斯', '小法', '卡牌', '压缩', '蛇女']
    print(heroes)
    heroes[0] = "王八蛋"
    print(heroes)
    

列表运算

  • 列表1 + 列表2 : 将两个列表从左到右合并为一个新列表,元素顺序不变

    A = [10,20,30]
    B = [100,200]
    C  = A + B
    print(C)
    print(A + A)
    
  • 整数 * 列表 ( 列表 * 整数) : 将列表中的元素按照顺序重复N次

    from random import  randint
    list_A = []
    for i in range(121):
        list_A.append(randint(50,100))
    print(list_A) #创建一个随机数列
    print(list_A* 3)  #将列表中的元素重复3次,有返回值
    
  • 比较大小,比较的是第一对不相等的元素的大小,相同下标位置的元素.返回值是True 或者False

    print([10,20,30]>[2,20,400,500])
    print([10,20,30]>[200,20,400,500]) 
    
  • in 和not in 判断元素是否在列表中

    print(10 in [[10,20],30])	#False
    print([10,20] in [10,20,30])	#False,[10,20]是一个元素
    print(10 and 20 in [10,20,30])	#True
    

相关函数

  • sum(数字序列) : 求数字序列中所有元素的数值的和

    scores = [98, 65, 44, 77, 99,89, 78]
    print(sum(scores))
    
  • max(数字序列)或者min(数字序列),求序列中最大,或者最小的元素,先假设,再更新

    scores = [98, 65, 44, 77, 99,89, 78]
    max_score = scores[0]
    for i in scores:
        if i > max_score:
            max_score = i
    print(max_score)
    print(max(scores))
    print(min(scores))
    
  • sorted(序列) - 将序列中的元素按照从小到大的方式排序,创建一个新列表进行存储,返回值为一个列表,有参数reverse,默认为False,表从小到大,True表示从大到小,有返回值,可以直接打印,没有返回值,打印为None

    scores = [98, 65, 44, 77, 99,89, 78]
    print(sorted(scores))
    print(scores)
    print(sorted(scores,reverse=True))
    """
    [44, 65, 77, 78, 89, 98, 99]
    [98, 65, 44, 77, 99, 89, 78]
    [99, 98, 89, 78, 77, 65, 44]
    """
    
  • len(序列) - 统计序列中所有元素的个数

    scores = [98, 65, 44, 77, 99,89, 78]
    print(len(scores))
    print(len("sjhfjbhdd"))
    
  • list(序列) - 将其他数据强行转换为列表,其他任何序列都能转换成列表,序列中的元素转换成列表中的元素

    result = list("djdnajvnjfa2423")#['d', 'j', 'd', 'n', 'a', 'j', 'v', 'n', 'j', 'f', 'a', '2', '4', '2', '3']
    print(result) #
    

相关方法

  • list.clear() - 清空列表

    nums = [10, 20, 30]
    print(nums)
    nums.clear()
    print(nums)   # 在列表中将所有元素清空,清除,,和nums = [],不一样,后者申请了2次内存
    
  • list.count(元素) - 统计列表中某个元素的个数

    scores = [98, 65, 44, 77, 99, 89, 78]
    print(scores.count(98))
    print(scores.count(100))
    
  • list.extend(序列) - 将序列中的元素全部添加到列表中去,可以是任何类型的数据,没有返回值

    scores = [98, 65, 65, 77, 99, 89, 78]
    scores.extend([90, 100, "adc"])
    print(scores)  # [98, 65, 65, 77, 99, 89, 78, 90, 100, 'adc']# 同append相比,可以一次追加多个元素
    
  • list.index() - 获取列表中指定元素的下标,不存在则报错,有多个则只识别第一个

    scores = [98, 65, 65, 77, 99, 89, 78]
    print(scores.index(90))
    print(scores.index(65))
    
  • list.reverse() - 将列表倒序

    scores.reverse()
    
  • list.sort() - 列表专用排序,直接作用于原列表,参数reverse默认值为False,表示从小到大.

    scores = [98, 65, 65, 77, 99, 89, 78]
    scores.sort(reverse=True)
    print(scores) # 表示从大到小, 默认从小到大
    

推导式

  • [表达式 for 变量 in 序列] 表示在序列中取元素,带入表达式中进行运算,返回元素存储在新列表中

    print([i % 10 for i in nums]) # 打印num中元素的个位数
    
  • [表达式 for 变量 in 序列 if 条件语句] 对原序列进行有条件的筛选,在序列中取出元素进行表达式计算,返回的元素,存储在新列表中

nums = [10, 23, 89, 67,45,56]
print([i % 10 for i in nums if i % 2 !=0])

1. 基础题

  1. 已知一个数字列表,打印列表中所有的奇数

    scores = [10,58,79,63,85,91,84,95,99,67]
    print([i for i in scores if i % 2 != 0])
    
  2. 已知一个数字列表,打印列表中所有能被能被3整除但是不能被2整除的数

    scores = [10,58,79,63,85,71,63,91,84,95,99,67]
    print([i for i in scores if i % 2 != 0 and i % 3 == 0])
    
  3. 已知一个数字列表,计算所有偶数的和

    scores = [10,58,79,63,85,71,63,91,84,95,99,67]
    list_sum = [i for i in scores if i % 2 == 0]
    print(sum(list_sum))
    
  4. 已知一个数字列表,统计列表中十位数是1的数的个数

    scores = [110, 518, 79, 63, 815, 71, 623, 931, 814, 945, 919, 657]
    count = 0
    for i in scores:
        if i %100 //10 == 1:
            count += 1
    print(count)
    
  5. 已知一个列表,获取列表中下标为奇数是所有元素(从0开始的下标值)

    例如: list1 = [10, 20, 5, 34, 90, 8]

    结果:[20, 34, 8]

    list1 = [10, 20, 5, 34, 90, 8]
    list2 = []
    for i in range(len(list1)):
        if i % 2 != 0:
            list2.append(list1[i])
    print(list2)
    
  6. 已知一个数字列表,将列表中所有元素乘以2

    例如: nums = [10, 3, 6, 12] 乘2后: nums = [20, 6, 12, 24]

    nums = [10, 3, 6, 12]
    nums = [i * 2 for i in nums]
    print(nums)
    
  7. 已知一个列表,获取列表的中心元素

    例如:nums = [10, 2, 6, 12] -> 中心元素为: 2和6

    ​ nums = [10, 2, 6, 12, 10] -> 中心元素为:6

    nums = [10, 2, 6, 12, 10]
    if len(nums) % 2 == 0:
        index = int(len(nums) / 2)
        print("中心元素为:", nums[index - 1], " , ", nums[index])
    else:
        index = int((len(nums) - 1) / 2)
        print("中心元素为:", nums[index])
    
  8. 已知一个列表,获取列表中所有的整型元素

    例如:list1 = [10, 1.23, ‘abc’, True, 100, ‘hello’, ‘20’, 5]

    ​ 结果是: [10, 100, 5]

    list1 = [10, 1.23, 'abc', True, 100, 'hello', '20', 5]
    print([i for i in list1 if type(i) == type(1)])
    

2. 进阶题

  1. 定义一个列表保存多个学生的分数,删除列表中所以低于60分的值

    例如: scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66] 删除后: scores = [60, 89, 99, 80, 71, 66]

    scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66]
    scores = [i for i in scores if i >= 60]
    print(scores)
    
  2. 已知一个列表保存了多个学生的姓名,要求去掉列表中重复的名字

    例如:names = [‘小明’, ‘张三’, ‘李四’, ‘张三’, ‘张三’, ‘小明’, ‘王五’, ‘王五’]

    ​ 去重后:names = [‘小明’, ‘张三’, ‘李四’, ‘王五’]

    names = ['小明', '张三', '李四', '张三', '张三', '小明', '王五', '王五']
    names_new = []
    for i in names:
        if i not in names_new:
            names_new.append(i)
    print(names_new)
    
    
  3. 已知一个数字列表,获取列表中值最大的元素 (不能使用max函数)

    scores = [110, 518, 79, 63, 815, 71, 623, 931, 814, 945, 919, 657]
    sum_num = scores[0]
    for i in scores:
        if i > sum_num:
            sum_num = i
    print(sum_num)
    
  4. 已知两个有序列表(列表中的元素已经按照从小到大的方式排好序),要求合并两个列表,合并后元素还是从小到大排序

    例如: list1 = [10, 23, 39, 41, 52, 55, 80] list2 = [9, 38, 55, 70]

    合并后的结果: [9, 10, 23, 38, 39, 41, 52, 55, 55, 70, 80]

    list1 = [10, 23, 39, 41, 52, 55, 80]
    list2 = [9, 38, 55, 70]
    list3 = list1 + list2
    list3.sort()
    print(list3)
    
  5. 已知一个有序数字列表(从小到大),输入任意一个数字,将输入的数字插入列表中,要求插入后列表仍然保持从小到大排序的关系

    例如: list1 = [10, 23, 45, 67, 91] 输入: 50 -> list1 = [10, 23, 45, 50, 67, 91]

    list1 = [10, 23, 45, 67, 91]
    num = int(input("请输入你要插入的数:"))
    list1.append(num)
    list1.sort()
    print(list1)
    
  6. 创建一个列表,列表中有10个数字, 保证列表中元素的顺序,对列表进行排重,并对列表使用进行降序排序

例如:[70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
		--- 去重之后 [70, 88, 91, 107, 234, 177, 282, 197]
  	---- 降序排序 [282, 234, 197, 177, 107, 91, 88, 70]
list1 = [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
list2 = []
for i in list1:
    if i not in list2:
        list2.append(i)
list2.sort(reverse=True)
print(list2)
  1. 利用列表推导式, 完成以下需求

a. 生成一个存放1-100中各位数为3的数据列表

结果为 [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
print([i for i in range(100) if i % 10 == 3])

b. 利用列表推到是将 列表中的整数提取出来

例如:[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
list1 = [True, 17, "hello", "bye", 98, 34, 21]
print([i for i in list1 if type(i) == int])

c.利用列表推导式 存放指定列表中字符串的长度

例如: ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
list1 = ["good", "nice", "see you", "bye"]
print([len(i) for i in list1])

d. 利用列表推导式删除列表中整数个位数小于5的元素

例如:[24, 'abc', 99, True, 21, 38, 'hello'] --- ['abc', 99, True, 38, 'hello']
list1 = [24, 'abc', 99, True, 21, 38, 'hello']
[list1.remove(i) for i in list1 if type(i) == int and i % 10 < 5]
print(list1)

e. 利用列表推导式获取元素是元组的列表中每个元组的最后一个元素

例如:[(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)]  --- [30, 'hello', 3.4, False]
list1 = [(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)]
print([i[-1] for i in list1])

f.利用列表推导式将数字列表中所有的奇数乘以2,所有的偶数除以2

例如: [23, 4, 67, 88, 90, 21]  -> [46, 2, 134, 44, 45, 42]
list1 = [23, 4, 67, 88, 90, 21]
list2 = [i * 2 if i % 2 != 0 else int(i/2)  for i in list1 ]
print(list2)
  1. 已知一个列表获取列表中指定元素所有的下标

    例如:[10, 20, 34, 10, 9, 78]
    10的下标:[0, 3]
    20的下标:[1]
    30的下标:[]
    
    list1 = [10, 20, 34, 10, 9, 78]
    list2 = []
    int_num =int(input("请输入您想查询下标的数:"))
    for i in range(len(list1)):
        if list1[i] == int_num:
            list2.append( i)
    print(int_num,"对应的下标为:",list2)
    
    
  2. *已知一个数字列表,写程序判断这个列表时候是连续递增列表。

    例如:
    [1, 2, 3, 4, 5]   -> True
    [23, 45, 78, 90]  -> True
    [1, 3, 2, 4, 5]	-> False
    
    list1 = [1, 2, 3, 4, 5]
    flag = True
    min_num = list1[0]
    for i in list1:
        if i >= min_num:
            min_num = i
            print(111)
        else:
            break
    if min_num == list1[-1]:
        flag =True
    else:
        flag = False
    print(flag)
    
  3. 已知两个列表,将两个列表按照下面的规律交叉合并

    A = [10, 20, 30, 40, 50]
    B = [100, 200, 300]
    结果:[10, 100, 20, 200, 30, 300, 40, 50]
    
    A = [10, 20, 30, 40, 50]
    B = [100, 200, 300]
    C = []
    for i in range(len(B)):
        C.append(A.pop(0))
        C.append(B.pop(0))
    C = C + A
    print(C)
    
  4. 已知两个有序列表,将两个列表合并,合并后的新列表中元素仍然是递增列表

    A = [10, 20, 30, 40, 50]
    B = [25, 44, 60]
    结果:[10, 20, 25, 30, 40, 45, 50, 60]
    
    A = [10, 20, 30, 40, 50]
    B = [25, 44, 60]
    C = A +B
    C.sort()
    print(C)
    
    C = []
    A = [10, 20, 30, 40, 50]
    B = [25, 44, 60]
    while True:
        if A[0] < B[0]:
            C.append(A.pop(0))
        else:
            C.append(B.pop(0))
        if A == [] or B == []:
            break
    print(C + A +B)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,`datetime` 模块提供了一系列处理日期和时间的函数和类。使用 `datetime` 模块可以获取当前日期和时间,也可以进行日期和时间的加减、格式化等操作。下面是 `datetime` 模块的一些常用语法: ```python import datetime # 获取当前日期和时间 now = datetime.datetime.now() # 根据指定的日期和时间创建 datetime 对象 dt = datetime.datetime(year, month, day, hour, minute, second, microsecond) # 获取 datetime 对象的各个属性 year = dt.year month = dt.month day = dt.day hour = dt.hour minute = dt.minute second = dt.second microsecond = dt.microsecond # 格式化 datetime 对象 formatted = dt.strftime(format) # 对 datetime 对象进行加减操作 delta = datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks) new_dt = dt + delta # 将字符串转换成 datetime 对象 dt = datetime.datetime.strptime(date_string, format) ``` 上述语法中,`datetime` 模块提供了 `datetime` 类和 `timedelta` 类来处理日期和时间。`datetime` 类表示一个日期和时间,而 `timedelta` 类表示两个日期或时间之间的时间差。 使用 `datetime.datetime.now()` 方法可以获取当前的日期和时间。使用 `datetime.datetime(year, month, day, hour, minute, second, microsecond)` 方法可以根据指定的日期和时间创建一个 `datetime` 对象。可以使用 `datetime` 对象的各个属性(如 `year`、`month`、`day`、`hour`、`minute`、`second` 和 `microsecond`)分别获取年、月、日、时、分、秒和微秒的值。 使用 `datetime.datetime.strftime(format)` 方法可以将 `datetime` 对象格式化为指定的字符串。可以使用标准格式代码和自定义格式代码来控制输出格式。例如,`%Y` 表示四位数的年份,`%m` 表示两位数的月份,`%d` 表示两位数的日期,`%H` 表示24小时制的小时数,`%M` 表示两位数的分钟数,`%S` 表示两位数的秒数。 使用 `datetime.timedelta()` 方法可以创建一个时间差对象,可以对 `datetime` 对象进行加减操作。可以使用 `days`、`seconds`、`microseconds`、`milliseconds`、`minutes`、`hours` 和 `weeks` 参数来指定时间差的值。 使用 `datetime.datetime.strptime(date_string, format)` 方法可以将字符串转换为 `datetime` 对象。可以使用与 `strftime()` 方法相同的格式代码来指定输入字符串的格式。 以上是 `datetime` 模块的一些常用语法,可以根据需要进行选择和组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值