【Python】第7次练习:组合数据类型——列表元素的积,重复元素判定A,编辑求集合的最大值和最小值,大多数元素A
1、列表元素的积
题目:一个由n(n>1)个数字组成的列表 ls,输出一个列表lt,其中lt中第i个元素等于ls中除ls[i]之外所有元素的乘积。
from functools import reduce
import operator
import functools
a=eval(input())
ls=list(a)
i=0
lt=list(a)
list_x=[]
while i<(len(lt)):
ls[i]=1
k = functools.reduce(operator.mul, ls, 1)
list_x.append(k)
ls=list(a)
i=i+1
else:
print(list_x)
2、重复元素判定A
题目:接收用户输入的一个列表,如果列表中元素存在重复,则返回True,否则返回False。
n=eval(input())
lst=list(n)
set_lst=set(lst)
if len(set_lst)==len(lst):
print('False')
else:
print('True')
3、编辑求集合的最大值和最小值
题目:已知集合A包含5个元素,分别是21, 234,-32,3,-55,请编程实现以下功能:
- 输出集合A
- 输出集合A中的最大值
- 输出集合A中的最小值
# 按要求输入集合A
A = {21, 234,-32,3,-55}
#求集合A的最大值
A_Max =234
#求集合A的最小值
A_Min =-55
# 按要求输出结果
print("集合A是:{0} \n 集合A的最大值是:{1} \n 集合A的最小值是:{2}".format
(A, A_Max, A_Min))
4、大多数元素A
题目:接收一个列表,找出其中数量最多的元素,如果元素数量相同,选择列表中靠前的元素输出。
from collections import Counter
word_list=eval(input())
word_counter ={}
for word in word_list:
if word in word_counter:
word_counter[word] +=1
else:
word_counter[word] = 1
popular_word =sorted(word_counter, key = word_counter.get, reverse = True)
top = popular_word[0]
print(top)