-
生成50-300之间可重复的 10个数据 存放于列表中, 保证列表中元素的顺序,对列表进行排重,并对列表使用排序算法进行降序排序
# 例如:随机生成了 [70, 88, 91, 70, 107, 234, 91, 177, 282, 197] # 去重之后 [70, 88, 91, 107, 234, 177, 282, 197] # 降序排序 [282, 234, 197, 177, 107, 91, 88, 70]
import random nums = random.choices(range(50, 301), k=10) new_list = [] for i in nums: if i not in new_list: new_list.append(i) for j in range(1, len(new_list)): for k in range(len(new_list) - j): if new_list[k] < new_list[k + 1]: new_list[k], new_list[k + 1] = new_list[k + 1], new_list[k] print(new_list)
-
用列表推导式, 完成以下需求
- 生成一个存放1-100中个位数为3的数据列表
- 利用列表推到是将列表中的整数提取出来 .
例如:[True, 17, “hello”, “bye”, 98, 34, 21] — [17, 98, 34, 21]
nums = [i for i in range(3, 94, 10)] print(nums) list1 = [True, 17, "hello", "bye", 98, 34, 21] result = [i for i in list1 if type(i) == int] print(result)
-
获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:[3]
例如:nums = [1, 2, 2, 3, 3] —> 打印:[2, 3]nums = [1, 2, 2, 3, 3] count_most = nums.count(nums[0]) num_most = [] for i in nums[1:]: if nums.count(i) > count_most: count_most = nums.count(i) for j in nums: if nums.count(j) == count_most: if j not in num_most: num_most.append(j) print(num_most) # 讲解 num_list = [] for i in nums: if nums.count(i) > count: count = nums.count(i) num_list.clear() num_list.append(i) elif nums.count(i) == count and i not in num_list: num_list.append(i) print(num_list)
005-列表练习题
于 2022-06-27 20:50:53 首次发布