python 中 for使用小技巧

1 testDict = {i: i * i for i in xrange(10)}
2 testSet = {i * 2 for i in xrange(10)}
3  
4 print(testSet)
5 print(testDict)
6  
7 #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
8 #{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

注:两个语句中只有一个 <:> 的不同,另,在 Python3 中运行上述代码时,将 <xrange> 改为 <range>。

原文地址:https://www.cnblogs.com/royfans/p/7194280.html