标签:frequency and print strong enc bad 列表 alice 方法
找到嵌套列表中名字含有两个‘e‘的所有名字
1 names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘], 2 [‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]] 3 l4 = [name for i in names for name in i if name.count(‘e‘) == 2 ] 4 print(l4)
执行输出:
[‘Jefferson‘, ‘Wesley‘, ‘Steven‘, ‘Jennifer‘]
列表推导式,最多不超过3个for循环
判断只能用一个
字典推导式
将一个字典的key和value对调
1 mcase = {‘a‘: 10, ‘b‘: 34} 2 mcase_frequency = {mcase[k]: k for k in mcase} 3 print(mcase_frequency)
执行输出:
{10: ‘a‘, 34: ‘b‘}
集合推导式
计算列表中每个值的平方,自带去重功能
1 squared = {x**2 for x in [1, -1, 2]} 2 print(squared) 3 # Output: set([1, 4])
执行输出:
{1, 4}
1 l_obj = (‘python%s期‘ % i for i in range(1,12)) 2 print(l_obj)
执行输出:
<generator object <genexpr> at 0x000002DDBEBADE60>
结果是一个生成器对象
如何取值呢?使用__next__方法
1 l_obj = (‘python%s期‘ % i for i in range(1,12)) 2 #print(l_obj) 3 print(l_obj.__next__()) 4 print(l_obj.__next__()) 5 print(l_obj.__next__())
执行输出:
python1期
python2期
python3期
标签:frequency and print strong enc bad 列表 alice 方法
原文地址:https://www.cnblogs.com/sky77/p/9673372.html