简体   繁体   English

Python习惯用法跳过匹配条件的第一行

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

I have a tab delimited data that looks like this: 我有一个制表符分隔的数据,看起来像这样:

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 

What I want to do is to parse the above data. 我想做的就是解析以上数据。 But first will have to skip the line that starts with Probes . 但是首先必须跳过以Probes开头的行。 But why this line failed? 但是为什么这条线失败了? What is the most common Pythonesque way to deal with these problem? 解决这些问题的最常见的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)

The pythonic way to deal with this is next() 处理此问题的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)

try: 尝试:

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

or: 要么:

if "Probes" in row:

or: 要么:

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

csv.reader returns you list of tuples from row split by delimiter. csv.reader从分隔符分隔的行中返回元组列表。 You tried to use re o list/tuple, while it works on strings only. 您尝试使用re o list / tuple,但它仅适用于字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM