>>> dict={'a':1,'b':2, 'c':3, 'd':4, 'e':5}
>>> {str(x):2*x for x in range(5)}
{'0': 0, '1': 2, '2': 4, '3': 6, '4': 8}
>>> {str(x):2*x for x in range(5) if x%2==0}
{'0': 0, '2': 4, '4': 8}
>>> {str(x):2*x if x%2==0 else str(2*x):x for x in range(5)} # 还未支持
File "<stdin>", line 1
{str(x):2*x if x%2==0 else str(2*x):x for x in range(5)} # 还未支持
^
SyntaxError: invalid syntax
>>> {x:2*y for x,y in dict.items()}
{'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}
python 字典推导
最新推荐文章于 2024-09-05 10:28:02 发布