Python的早期练习题-2

    xiaoxiao2022-07-03  151

    练习

    1、- 使用列表推导式找出单词长度大于n的单词

    ls = ["google","apple","hello","battle"] n = 5 for item in ls: if len(item) > n: print(item) google battle

    2、- 使用列表推导式寻找两个列表中的相同元素

    ls1 = ["google","apple","hello","battle"] ls2 = ["gooogle","dpple","hello","baattle"] for item1 in ls1: for item2 in ls2: if item1 == item2 : print(item1) hello ls1 = ["google","apple","hello","battle"] ls2 = ["gooogle","dpple","hello","baattle"] [a for a in ls1 for b in ls2 if a == b] ['hello']

    3、- 去除一个列表中相领且重复的元素。

    ls = ["google","apple","apple","hello","battle"] for i in range(len(ls)-2): #注意index值,i+1 < len(ls)-1 if ls[i+1] == ls[i]: ls.remove(ls[i]) print(ls) ['google', 'apple', 'hello', 'battle']

    4、用户名密码对应

    给定两个列表,一个存放用户名,一个存放密码。请将用户名和密码按顺序进行对应为一个元素。 ls_user = ["A","B","C"] ls_password = ["aa","bb","cc"] ls = {} if len(ls_user) == len(ls_password): for i in range(len(ls_user)): ls[ls_user[i]] = ls_password[i] else: print("用户名和密码不一致,请检查!") print(ls) {'B': 'bb', 'A': 'aa', 'C': 'cc'}

    5、使用列表推导式计算笛卡尔积(组合)

    A = [1,2,3] B = [4,5,6] [a*b for a in A for b in B ] [4, 5, 6, 8, 10, 12, 12, 15, 18]

    6、词频统计

    利用dict统计词频对每个参数进行判断,若在则对应的value+1否则根据该字符创建一个key并且value设置为1最后输出该词典 ls=['sklearn','AI','julyedu.com','Caffe','AI','sklearn'] Dic = {} for i in range(len(ls)): Dic[ls[i]] = Dic.get(ls[i],0) + 1 print(Dic) {'AI': 2, 'Caffe': 1, 'julyedu.com': 1, 'sklearn': 2}

    7、- 实现行列互转

    a = [[1,2,3],[4,5,6],[7,8,9]] import numpy as np a = np.array(a) print(a) print(a.T) [[1 2 3] [4 5 6] [7 8 9]] [[1 4 7] [2 5 8] [3 6 9]]

    8、- fib数列[数组实现]

    def fibo_list(k): ls = [] if k < 1: print("worning!") else: for i in range(k): if i == 0 : ls.append(1) continue elif i == 1: ls.append(1) continue else: ls.append(ls[i-2]+ls[i-1]) return ls fibo_list(3) [1, 1, 2]

    作业

    9、-输入含有[]的字符串,输出对中括号出现规则的检测结果

    StrInput = input("请输入带[]的英文:") #[s]]][[]] if StrInput[0] == "]": print("Not Ok") lsA = [] lsB = [] for i in range(len(StrInput)): if StrInput[i] == "[": lsA.append(i) if StrInput[i] == "]": lsB.append(i) if len(lsA) == len(lsB): a = 0 for i in range(len(lsA)): if lsA[i] >= lsB[i]: a += 1 print("Not Ok") break if a == 0: print("OK") 请输入带[]的英文:[][[a]]][ Not Ok

    感悟收获

    在最后的作业题中,对于问题的理解有差异,想不太清楚对于检索时候的位置,以及其是否为对应的,要多加练习;今天的视频因为时间关系只看了一半,所以对于里面题目涉及的内容,可能会使用的方法与今天的课程方法不一致,自己的方法可能效率上会低;在写代码的时候,开始考虑运行效率问题,比如在迭代问题上,Fibonacci数列,会想到储存上次的值,下一次进行调用,节约运算时间。
    最新回复(0)