python基础升级第二节


练习一: 使用循环和列表推导找出单词长度大于某个
数字的单词
■ words = ["apple", "banana", "orange",
"peach","kiwi"]
num = input('请输入单词最大长度') #注意输入的str类型
words = ["apple", "banana", "orange","peach","kiwi"]
[x for x in words if len(x)>=int(num)]

num = input('请输入单词最大长度') #注意输入的str类型
words = ["apple", "banana", "orange","peach","kiwi"]
for i in range(len(words)):
if len(words[i])>=int(num) :
print(words[i])

练习二:寻找两个列表中的相同元素
■ l1=[1,2,5]
■ l2=[6,2,7]

l1 = [1,2,4,5]
l2 = [6,2,7,4]
[x for x in l1 if x in l2]

l1 = [1,2,4,5]
l2 = [6,2,7,4]
[x for x in l1 if x in l2]

练习三:去除一个列表中相领且重复的元素。
■ l1=[1,2,3,4,4,4,4,4,4,5,6,6,8,8,12,12,12,12,13]

l1=[1,2,3,4,4,4,4,4,4,5,6,6,4,4,4,8,8,12,12,12,12,15]

l2 =[] #如果少了这一行代码,则最后会出现两行结果
l2.append([l1[item] for item in range(len(l1)) if l1[item] != l1[item-1]] or item ==1)
print(l2)

练习四:用户名密码对应
■ 给定两个列表,一个存放用户名,一个
存放密码。请将用户名和密码按顺序进
行对应为一个元素。
■ Username=[‘jack’,’bob’,’john’]
■ Password=[‘123’,’859’,’hello’]

Username=['jack','bob','john']
Password=['123','859','hello']
l1=list(zip(Username,Password))
print('l1 = ',l1)

练习五:使用列表推导式,打印出颜色与尺寸的(组
合)
▪ colors=['black','white']
▪ sizes=['S','M','L']
colors=['black','white']
sizes=['S','M','L']
[(x,y) for x in colors for y in sizes]

练习六:词频统计
■ l1=['sklearn','AI','julyedu.com','Caffe','AI','skle
arn‘]
■ 对l1包含的单词,利用dict统计词频
■ 对每个参数进行判断,若在则对应的value+1
■ 否则根据该字符创建一个key并且value设置
为1
■ 最后输出该词典

l1=['sklearn','AI','julyedu.com','Caffe','AI','sklearn']
dict = {}
for i in range(len(l1)):
if l1[i] in dict.keys():
dict[l1[i]] += 1
else:
dict[l1[i]] = 1
print(dict)

练习七:实现行列互转
■ arr= [[1, 2, 3], [4, 5, 6], [7,8, 9], [10, 11, 12]]
arr= [[1, 2, 3], [4, 5, 6], [7,8, 9], [10, 11, 12]]
result = []

for i in range(len(arr[0])):
result.append([arr[x][i] for x in range(len(arr))]) #列表推导式返回的是一个列表,result.append()添加的是一个列表
print(result)

练习八:实现求指定长度的Fibonacci 数列
▪ Fib数组初始为[0,1]
■ 分别要求使用循环和数组实现
num = input('请输入Fibonacci数个数') #注意输入的str类型
l1 = [0,1]
if int(num) <= 2:
pass
else:
for i in range(int(num)):
num = l1[i] +l1[i+1]
l1.append( num)
print('l1=',l1)

作业: [ ]对应检查

str = input('请输入含有中括号的字符串')
num = 0

for char in str:
if char=='[':
num +=1
elif char==']':
num -=1
else:
pass
if num < 0:
break

if num == 0:
print('OK')
else:
print('NOT OK')
已邀请:

要回复问题请先登录注册

返回顶部