各种推导式
找出30以内所有能被3整除的数
l = [i for i in range(30) if i % 3 == 0] print(list(range(0,30,3))) print(l)
找出30以内所有能被3整除的数的平方
l = [i**2 for i in range(30) if i % 3 == 0] print(l) def square(x): return x*x l = [square(i) for i in range(30) if i % 3 == 0]
找到嵌套列表中名字含有两个‘e’的所有名字
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] print([name for lst in names for name in lst if name.count('e') >= 2]) # 注意遍历顺序,这是实现的关键 # 上面的写法不利于代码可读,但是代码简洁
将一个字典的key和value对调
mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
合并大小写对应的value值,将k统一成小写
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()} print(mcase_frequency)
计算列表中每个值的平方,自带去重功能
squared = {x**2 for x in [1, -1, 2]} print(squared) # Output: set([1, 4])