1.创建一个列表,列表中有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]
list1 = [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
list2 = []
for x in list1:
if x not in list2:
list2.append(x)
print(list2)
list2.sort(reverse=True)
print(list2)
2.利用列表推导式, 完成以下需求
a. 生成一个存放1-100中各位数为3的数据列表
结果为 [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
list1 = [x for x in range(1,101) if x %10 ==3]
print(list1)
b. 利用列表推到是将 列表中的整数提取出来
例如:[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
list1 = [True, 17, "hello", "bye", 98, 34, 21]
list2 = [x for x in list1 if type(x) == int]
print(list2)
c.利用列表推导式 存放指定列表中字符串的长度
例如: ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
list1 = ["good", "nice", "see you", "bye"]
list2 = [len(x) for x in list1]
print(list2)
d. 利用列表推导式删除列表中整数个位数小于5的元素
例如:[24, 'abc', 99, True, 21, 38, 'hello'] --- ['abc', 99, True, 38, 'hello']
list1 = [24, 'abc', 99, True, 21, 38, 'hello']
list2 = [x for x in list1 if not (type(x)==int and x%10 <5)]
print(list2)
e. 利用列表推导式获取元素是元组的列表中每个元组的最后一个元素
例如:[(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)] --- [30, 'hello', 3.4, False]
list1 = [(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)]
list2 = [x[-1] for x in list1]
print(list2)
f.利用列表推导式将数字列表中所有的奇数乘以2,所有的偶数除以2
例如: [23, 4, 67, 88, 90, 21] -> [46, 2, 134, 44, 45, 42]
list1 = [23, 4, 67, 88, 90, 21]
list2 = [x *2 if x %2 else x /2 for x in list1]
print(list2)