2016-01-15 174 views
1

我想使用csv.DictReader讀取一列,並根據下面的值,我想打印不同列中相應值之間的差異:value below - 上面的值。使用csv.DictReader進行迭代

我寫這個劇本:

import csv 

next=None 
last = None 
test_file = 'data.tsv' 
csv_file = csv.DictReader(open(test_file, 'rU'), delimiter='\t') 
for row in csv_file: 
    if row['GT'] == "0/1": 
     genotype = row['GT'] 
     if next is not None: 
      if next == "0/1": 
       position = int(row['pos']) 
       if last is not None: 
        print (position - last) 
       last = position 
     next = genotype 

當我data.tsv運行(見下文),它做什麼,它該做的,這是打印80.在列GT,0/1發生0/1一次之後,和832398-832318 = 80

pos GT 
815069 0/0 
825069 0/1 
825410 ./. 
830181 1/1 
832318 0/1 
832398 0/1 
832756 0/0 

然而,當我設置

如果下一個== 「0/0」:( - >如果第一GT = 0/1和接下來的GT = 0/0,打印出 對應的值在pos列中,即832756-832398 = 358)

它不打印任何東西!當改變時

if next ==「./。」

它什麼都不做

import csv 

next=None 
last = None 
test_file = 'data.tsv' 
csv_file = csv.DictReader(open(test_file, 'rU'), delimiter='\t') 
for row in csv_file: 
    if row['GT'] == "0/1": 
     genotype = row['GT'] 
     if next is not None: 
      **if next == "0/0":** 
       position = int(row['pos']) 
       if last is not None: 
        print (position - last) 
       last = position 
     next = genotype 

任何想法,這可能是爲什麼? 感謝您的幫助!讓我知道如果我要澄清的問題(Python的初學者)的說明

問候 喬安娜

回答

1

在第一個腳本變量next是混亂的,實際上它是不是未來,但目前GT。劇本只是偶然的,因爲兩個GT都是平等的(所以順序無關緊要)。

正如你按行遍歷文件的行幾乎不可能向前看,而不是你可以回頭看看,到最後GT這樣比較當前GT:

import csv 

last_gt = None 
last_pos = None 
test_file = 'data.tsv' 
csv_file = csv.DictReader(open(test_file, 'rU'), delimiter='\t') 
    for row in csv_file: 
     curr_gt = row['GT'] 
     curr_pos = int(row['pos']) 
     if (curr_gt == "0/0") and (last_gt == "0/1"): # EDIT: 'and' instead of '&' 
      print(curr_pos - last_pos) 
     last_pos = curr_pos       # EDIT: delete 'else' statement 
     last_gt = curr_gt 
+1

我認爲這主要是正確的回答。我不確定'else'塊,可能last_whatever'值應該在循環結束時無條件地更新。另外,你應該在'if'條件下使用'和'運算符而不是'&'。後者是按位進行的,而且這種情況在這種情況下可以正常工作,因爲這兩個參數都是「bool」,但它可能無法正確運行其他上下文。例如,表達式'1和2'是'2'(這是truthy),而'1&2'是'0'(虛假)。 – Blckknght

+0

謝謝@Blckknght的解釋性評論。我認爲這是一個好點,因此我會編輯我的答案。 – Benjamin