没有使用列表解析:
1 x =[]2 for i in (1, 2, 3):3 x.append(i)4 5 """6 >>> x7 [1, 2, 3]8 """
列表解析式:
1 x = [i for i in (1, 2, 3)]2 """3 >>> x4 [1, 2, 3]5 """
多重列表解析:
1 x = [word.capitalize() 2 for line in ("hello world?", "world!", "or not") 3 for word in line.split()#空格分割 4 if not word.startswith("or")] 5 6 """ 7 >>> x 8 ['Hello', 'World?', 'World!', 'Not'] 9 10 """
创建一个字典和集合的方法也是一样的:
1 >>> {x: x.upper() for x in ['hello', 'world']}2 { 'world': 'WORLD', 'hello': 'HELLO'}3 4 >>> {x.upper() for x in ['hello', 'world']}5 set(['WORLD', 'HELLO'])6 >>>