列表
- filter + lambda函数
>>> import random
>>> l1 = [random.randint(-10, 10) for i in range(10)]
>>> print(l1)
[3, 8, -5, 4, -4, -5, -7, -8, -6, -7]
>>> print(list(filter(lambda x: x>0, l1)))
[3, 8, 4]
- 迭代器
>>> print([x for x in l1 if x>0])
[3, 8, 4]
集合
-
迭代器
>>> s1 = set(random.randint(-10, 10) for i in range(10)) >>> print(s1) {-10, -5, -1, 0, 3, 8, 9} >>> print({x for x in s1 if x >0}) {8, 9, 3}
字典
-
产生随机字典
# 产生随机字典 letters = 'abcdefghijklmnopqrstuvwxyz' l2 = [] l1 = [0 for i in range(len(letters))] d1 = {} for got_num in range(len(letters)): temp_int = random.randint(got_num+1, len(letters)) - got_num # 表示第temp_int个0,从1开始 current_num,i = 0, -1 while current_num < temp_int: i += 1 current_num += 1 if l1[i] == 0 else 0 # i 就是我们要找的位置 l2.append(i) l1[i] = 1 d1 = {letters[x]: random.randint(-10, 10) for x in l2} # 打印一下 print(d1)
-
d1的迭代
>>> d2 = {k:v for k,v in d1.items() if v>0} >>> print(d2) {'a': 9, 'b': 3, 'c': 5, 'd': 10, 'f': 3, 'i': 8, 'j': 2, 'n': 5, 'v': 1, 'w': 10, 'x': 3}