2016-02-16 37 views
0

我已經搜索了一個解決方案,但我一直無法找到一個,很奇怪。將列表中的某些索引值轉換爲int

我打開一個文件,其中包含以下內容。

Alex,10,0,6,3,7,4 
Bob, 6,3,7,2,1,8 

我想將score_list中的所有值從1-4索引值轉換爲整數。我試圖這樣做,但它只是不起作用。

score_list = [] 
    def opening_file(): 
     counter = 0 
     with open('scores.txt', newline='') as infile: 
      reader = csv.reader(infile) 
      for row in reader: 
       score_list.append(row[0:5]) 

      counter = 0 
      while counter != 5: 
       counter +=1 
       row[counter] = int(row[counter]) 
      print (score_list) 

    opening_file() 

,但它不工作,只是產生內row

[['Alex', '10', '0', '6', '3'], ['Bob', ' 6', '3', '7', '2']] 

,而不是[['Alex', 10, 0, 6, 3], ['Bob', 6, 3, 7, 2]]

回答

1

while環路row轉化值發生爲時已晚。每行的值已被複制(通過切片操作)到已添加到score_list的新列表中。無論如何,你只能在最後一行運行循環(假設你在問題中的縮進是正確的)。

嘗試這樣:

with open('scores.txt', newline='') as infile: 
    reader = csv.reader(infile) 
    for row in reader: 
     for i in range(1,5): 
      row[i] = int(row[i]) 
     score_list.append(row[0:5]) 

我使用的是一個範圍for循環,而不是一個while循環,只是因爲它更方便(一while循環版本可以工作得很好,它只是需要更多線路)。關鍵是要在reader的循環內更改row,並在將行分割爲appendscore_list之前。

+0

非常感謝。我發現所有的答案都很有幫助,但我特別發現了這個答案,因爲你確實記得在只添加行[0:5]的代碼中添加。 – TeeKayM

2

要轉換的項目這僅僅是一個一次性的變量。你也不需要那些多餘的工作,你可以簡單地將你的行解壓到namescores部分,並使用列表理解將數字轉換爲整數。

with open('scores.txt', newline='') as infile: 
    reader = csv.reader(infile) 
    for row in reader: 
     name, *scores = row 
     score_list.append([name] + [int(i) for i in scores]) 
+0

我想你不能連接任意iterables到 –

+0

@TamasHegedus對不起,我沒有得到你的列表。你的意思是*任意迭代* *? – Kasramvd

+0

我的意思是一個python 3.x'map'對象:'[name] + map(int,scores)' –

1

首先,代碼轉換row數組中的項目,但打印score_list數組。其次,因爲它改變了讀取器for循環外部的row變量,它只會改變最後一行。你可以做這樣的事情:

import csv 

def opening_file(): 
    with open('scores.txt', newline='') as infile: 
    return [[row[0]] + [int(x) for x in row[1:]] for row in csv.reader(infile)] 
score_list = opening_file() 
print(str(score_list))