在python中,詞典綜合提供了一種生成新詞典的簡潔方法。儘管它們與列表綜合相似,但存在一些顯著差異。
Setting a Single Value for Multiple Keys
To set the same value for multiple keys, you can use the following syntax:d = {n: n**2 for n in range(5)}d = {n: True for n in range(5)}This creates a dictionary with keys from 0 to 4, all with the value True.
Setting Multiple Values for Multiple Keys
As the question points out, it is not possible to specify multiple values for the使用字典理解的相同鍵。為了實現這一目標,您可以使用循環手動分配值或創建單獨的詞典,然後使用update()更新現有的詞典:d = {n: True for n in range(5)}
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3