7 小练习
7.1 计算能被3或5整除的1000以内的数字的和
print(sum(i for i in range(1,1000) if i%3==0 or i%5==0))
233168
7.2 移除列表中指定的数字
def removeNum(origin_list,num):
newlist=list(filter(lambda n:n!=num,origin_list))
newlist.sort(reverse=True)
return newlist
origin_list=[1,6,3,6,7,3,8,10,100]
print(removeNum(origin_list,6))
[100, 10, 8, 7, 3, 3, 1]
7.3 从排序好的列表中删除重复元素
def removeRepeat(sorted_list):
new_list=list(set(sorted_list))
new_list.sort()
return new_list
sorted_list=[1,3,3,5,5,8,10,10,100,100]
print(removeRepeat(sorted_list))
[1, 3, 5, 8, 10, 100]
7.4 从排序好的列表中删除重复元素,重复的数字最多出现两次
from collections import Counter
def removeThirdRepeat(origin_list):
counter={}
for character in origin_list:
if character not in counter.keys():
counter.setdefault(character,1)
else:
if counter[character]<2:
counter[character]+=1
else:
origin_list.remove(character)
# print(counter)
return origin_list
origin_list=[1,1,1,2,2,5]
print(Counter(origin_list))
print(removeThirdRepeat(origin_list))
Counter({1: 3, 2: 2, 5: 1})
[1, 1, 2, 2, 5]
7.5 判断一个字符串能否给另一个字符串做循环移位得到
def cycleMove(src_string,des_string):
new_string=src_string+src_string
if des_string in new_string:
return True
else:
return False
src='AABBCD'
des='CDAA'
print(cycleMove(src,des))
True
7.6 将包含在列表里的列表拆开
def SplitList(lis):
new_list=[]
for character in lis:
if type(character) is list:
new_list.extend(character)
else:
new_list.append(character)
return new_list
test_list=[[1,2,3],4,5,6]
print(SplitList(test_list))
[1, 2, 3, 4, 5, 6]
另一种简洁写法:
test_list=[[1,2,3],4,5,6]
new_list=[]
for character in test_list: new_list.extend(character) if type(character) is list else new_list.append(character)
print(new_list)
[1, 2, 3, 4, 5, 6]