Task4 列表、元组和字符串

列表练习题

1、列表操作练习

列表lst 内容如下

lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]

请写程序完成下列操作:

在列表的末尾增加元素15
在列表的中间位置插入元素20
将列表[2, 5, 6]合并到lst中
移除列表中索引为3的元素
翻转列表里的所有元素
对列表里的元素进行排序,从小到大一次,从大到小一次

编写程序如下:

lst=[2,5,6,7,8,9,2,9,9]
lst.append(15)
print(lst) 
lst.insert(5, 20)
print(lst)
lst.extend([2,5,6])
print(lst)
del lst[3]
print(lst)
lst.reverse()
print(lst) 
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)

[2, 5, 6, 7, 8, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
[2, 5, 6, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
[6, 5, 2, 15, 9, 9, 2, 9, 20, 8, 6, 5, 2]
[2, 2, 2, 5, 5, 6, 6, 8, 9, 9, 9, 15, 20]
[20, 15, 9, 9, 9, 8, 6, 6, 5, 5, 2, 2, 2]

2、修改列表

问题描述:

lst = [1, [4, 6], True]

请将列表里所有数字修改成原来的两倍

可以采用直接赋值的方法:

lst=[1,[4,6],True]
lst[0]=2
lst[1][0]=8
lst[1][1]=12
print(lst)

[2, [8, 12], True]

还可以建立函数实现批量类似列表的数据转换:

def double_list(lst):
    for index, item in enumerate(lst):
        if isinstance(item, bool):
            continue
        if isinstance(item, (int, float)):
            lst[index] *= 2
        if isinstance(item, list):
            double_list(item)
            
lst=[1,[4,6],True]
double_list(lst)
print(lst)

[2, [8, 12], True]

3、leetcode 852题 山脉数组的峰顶索引

如果一个数组k符合下面两个属性,则称之为山脉数组

数组的长度大于等于3

存在 i i i i i i >0 且 i < len ⁡ ( k ) − 1 i<\operatorname{len}(k)-1 i<len(k)1, 使得 k [ 0 ] < k [ 1 ] < … < k [ i − 1 ] < k [ j ] > k [ i + 1 ] … > k [ len ⁡ ( k ) − 1 ] \mathrm{k}[0]<\mathrm{k}[1]<\ldots<\mathrm{k}[\mathrm{i}-1]<\mathrm{k}[\mathrm{j}]>\mathrm{k}[\mathrm{i}+1] \ldots>\mathrm{k}[\operatorname{len}(\mathrm{k})-1] k[0]<k[1]<<k[i1]<k[j]>k[i+1]>k[len(k)1]

这个 i i i就是顶峰索引。

现在,给定一个山脉数组,求顶峰索引。

示例:

输入:[1, 3, 4, 5, 3]

输出:True

输入:[1, 2, 4, 6, 4, 5]

输出:False

题目分析:已知给定输入确定为山脉数组,则求顶峰索引也就是求山脉数组中最大值的索引。可以通过比较数组中相邻两个数据大小,求得最大值,并获得其索引,进一步求得山脉数组顶峰索引。

编写程序如下:

from typing import List

class Solution:
    def peakIndexInMountainArray(self, A: List[int]) -> int:
        max_value=0
        index=0
        for i in range(len(A)):
            if(A[i]>max_value):
                max_value=A[i]
                index=i
        return index

lst=[1, 3, 4, 7, 8, 5, 3]
object1=Solution()
print(object1.peakIndexInMountainArray(lst))

4
可以看到,虽然结果正确,但是编写的程序是针对普遍数组寻找最大值的情况,对于本题的山峰数组来说效率比较低,因此可以对程序进行改进:

from typing import List

class Solution:
    def peakIndexInMountainArray(self, A: List[int]) -> int:
        index=0
        left=0
        right=len(A)
        while left<right:
            center=(left+right)//2
            if (A[center]>A[center-1]) and (A[center]>A[center+1]):
                index=center
                break
            elif A[center]<A[center-1]:
                right=center
            else:
                left=center
        return index
    
lst=[1, 3, 4, 7, 8, 9, 5, 3]
object1=Solution()
print(object1.peakIndexInMountainArray(lst))

采用二分法的思想,使程序运行的效率提高。

元组练习题

1、元组概念

写出下面代码的执行结果和最终结果的类型.

(1, 2)*2
(1, )*2
(1)*2

输出执行结果及最终结果类型:

a=(1, 2)*2
b=(1, )*2
c=(1)*2
print(a,type(a))
print(b,type(b))
print(c,type(c))

(1, 2, 1, 2) <class ‘tuple’>
(1, 1) <class ‘tuple’>
2 <class ‘int’>
可以看到前两式子都是元组类型,第三个式子是整型。

2、拆包过程是什么?

a, b = 1, 2

上述过程属于拆包吗?

可迭代对象拆包时,怎么赋值给占位符?

首先要理解,什么是拆包

拆包的定义: 对于函数中的多个返回数据, 去掉元组, 列表 或者字典 直接获取里面数据的过程。

可以看到,根据定义,"1,2"属于一个元组,因此上述过程属于拆包。任何可迭代对象(列表、元祖、字符串、文件对象、迭代器和生成器等),都可以通过一个简单的赋值语句拆包并赋值给多个变量,但是要保证变量的数量和可迭代对象元素的数量一致。在可迭代对象拆包时,使用 _ 进行单个元素占位 ,或者使用 *_ 对连续多个元素进行占位。

字符串练习题

1、字符串函数回顾

怎么批量替换字符串中的元素?
怎么把字符串按照空格进⾏拆分?
怎么去除字符串⾸位的空格?

①可以采用replace()函数批量替换字符串中的元素,replace()函数用法如下:

replace(old, new [, max]) 把 将字符串中的old替换成new,如果max指定,则替换不超过max次。

eg:

str5 = 'I Love LsgoGroup'
print(str5.replace('I', 'We'))

We Love LsgoGroup

②采用split()函数按照空格拆分字符串,split()用法如下:

split(str="", num) 不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。

eg:

str5 = 'I Love LsgoGroup'
print(str5.split())

[‘I’, ‘Love’, ‘LsgoGroup’]

③可以采用lstrip()函数去除字符串⾸位的空格,lstrip()函数用法如下:
lstrip([chars]) 截掉字符串左边的空格或指定字符。

eg:

str5 = ' I Love LsgoGroup '
print(str5)
print(str5.lstrip())

I Love LsgoGroupI Love LsgoGroup

2、实现isdigit函数

题目要求

实现函数isdigit, 判断字符串里是否只包含数字0~9

def isdigit(string):
    """
    判断字符串只包含数字
    :param string:
    :return:
    """
    # your code here
    pass

编写程序如下:

def isdigit(string):
    """
    判断字符串只包含数字
    :param string:
    :return:
    """
    return string.isnumeric()

str="12345"
print(isdigit(str)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值