簡體   English   中英

Python習慣用法跳過匹配條件的第一行

[英]Python idiom to skip first line that match condition

我有一個制表符分隔的數據,看起來像這樣:

Probes  FOO BAR
1452463_x_at    306.564     185.705 
1439374_x_at    393.742     330.495 
1426392_a_at    269.850     209.931 
1433432_x_at    636.145     487.012 
1415687_a_at    231.547     175.008 
1424736_at  248.926     189.500 
1435324_x_at    244.901     225.842 
1438688_at  180.511     187.407 
1426906_at  206.694     218.913 

我想做的就是解析以上數據。 但是首先必須跳過以Probes開頭的行。 但是為什么這條線失敗了? 解決這些問題的最常見的Python風格是什么?

import sys
import csv
import re 

with open('Z100_data.txt','r') as tsvfile:
    tabreader = csv.reader(tsvfile,delimiter='\t')
    for row in tabreader:
        if re.match("^Probes",row):
            # He we try to skip the first line.
            continue
        else:

           print ', '.join(row)

處理此問題的pythonic方法是next()

with open('Z100_data.txt','r') as tsvfile
    tabreader = csv.reader(tsvfile,delimiter = '\t')
    next(tabreader) # skips the first line
    for row in tabreader:
        print ', '.join(row)

嘗試:

if re.match("^Probes",' '.join(row)):

要么:

if "Probes" in row:

要么:

if "Probes" == row[0].strip():

csv.reader從分隔符分隔的行中返回元組列表。 您嘗試使用re o list / tuple,但它僅適用於字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM