编程语言
首页 > 编程语言> > Python的早期练习题-2

Python的早期练习题-2

作者:互联网

练习

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、词频统计

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

感悟收获

标签:练习题,google,早期,Python,len,battle,ls,print,hello
来源: https://blog.csdn.net/weixin_43930330/article/details/90442878