2016-03-01 23 views
-2
dict = {0: ['2', '6'], 1: ['2'], 2: ['3']} 

print("Original: ") 
print(dict) 

for key,vals in dict.items(): 
    vals = [int(s) for s in vals] 

print("New: ") 
print(dict) 

輸出:正確的方法來改變一個字符串列表,列出整數

Original: 
{0: ['2', '6'], 1: ['2'], 2: ['3']} 
New: 
{0: ['2', '6'], 1: ['2'], 2: ['3']} 

我想不通爲什麼值列表是不會改變的,我曾嘗試在地圖()函數它也行不通,爲什麼?

回答

1

因爲您不會覆蓋字典中的實際值。試着做:

for key,vals in dict.items(): 
    dict[key] = [int(s) for s in vals] 

隨着詞典的理解,它實際上看起來好多了。我只是試圖展示你的代碼應該改變什麼。

2

在Python 3:

dict = {k: list(map(int, v)) for k, v in dict.items()} 
+0

在第一行 - 我想這對Python的2 - 你有一個錯誤。你應該把它改成像'dict(((k,list(map(int,v)))for k,v in d.items()))'因爲Python 2不支持dict生成器 –

+0

我在想關於Python 2.7的反向移植。我完全刪除第一行,因爲標籤有'python'和最新版本,所有應該旨在與Python 3一起工作。 – omikron

相關問題