python基础之字典推导式

字典推导式和列表推导式的使用方法类似,中括号该改成大括号。

例 1:交换key 和 value

>>> Dict={"name":"ma jun","age":23,"gender":"boy","job":"sales"}
>>> D={value:key for key,value in Dict.items()}
>>> D
{'ma jun': 'name', 23: 'age', 'boy': 'gender', 'sales': 'job'}

例 2:

>>> List=["America","China","Russia","England","Korea","India"]
>>> Dict={key:value for value,key in enumerate(List)}
>>> Dict
{'America': 0, 'China': 1, 'Russia': 2, 'England': 3, 'Korea': 4, 'India': 5}

集合推导式和列表推导式的使用方法也类似,使用大括号

例:

>>> Set={1,2,3,4,5,6,7,8,9}
>>> S={x*10 for x in Set}
>>> S
{70, 40, 10, 80, 50, 20, 90, 60, 30}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章