Python if语句 - 排除" - "

时间:2015-03-02 02:18:11

标签: python python-2.7

我正在从netcdf文件中读取数据,我注意到有些字段会被写入我的文件中作为" - "。

当我将内容变量打印到控制台时,其值为:  [-33.939999,151.03918,蒙面,蒙面,蒙面,蒙面,蒙面,蒙面,蒙面]

我已尝试使用以下代码块来检查该行是否包含屏蔽或" - "并写下这些价值观。它无法正常工作!

如何排除或检查这些值?

尝试:     如果"蒙面"不在内容中:         outputwriter.writerow(内容)         打印内容

更新

       with open(r'C:/output.csv', 'wb') as csvFile:
        outputwriter = csv.writer(csvFile, delimiter=',')
        for date_val in date_strings:
            header.append(date_val)
        outputwriter.writerow(header)
        for lat_index, lat in enumerate(lats):
            for lon_index, lon in enumerate(lons):
                content = [lat,lon]
                for time_index, time in enumerate(times[:]): 
                    data = value[time_index,lat_index,lon_index]
                    content.append(data)
                #outputwriter.writerow(content) 
                temp = content
                contentVal = (set(temp)-set(exclude))
                for item in contentVal:
                    outputwriter.writerow(item)
                    print item

更新2

from netCDF4 import Dataset, num2date
import csv

filename = "C:/netcdf.nc"

nc = Dataset(filename, 'r', Format='NETCDF4')

lats = nc.variables['latitude'][:] 
lons = nc.variables['longitude'][:]
sfc = nc.variables['Min_SFC'][:]

times = nc.variables['time']
dates = num2date(times[:],times.units)
date_strings = [date.strftime('%d-%m-%Y') for date in dates]

header =  ['Latitude', 'Longitude']
exclude = ['masked','--']

with open(r'C:/output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    for date_val in date_strings:
        header.append(date_val)
    outputwriter.writerow(header)
    for lat_index, lat in enumerate(lats):
        for lon_index, lon in enumerate(lons):
            content = [lat,lon]
            for time_index, time in enumerate(times[:]): 
                data = sfc[time_index,lat_index,lon_index]
                content.append(data) 
            contentVal = (set(content)-set(exclude))
            print "Content Val"
            print contentVal
            print "Content"
            print content
            outputwriter.writerow(contentVal)

2 个答案:

答案 0 :(得分:1)

您需要使用for循环。

for i in content:
    if i != "masked" or i != "--":
        outputwriter.writerow(i)
        print i

答案 1 :(得分:0)

我从未使用outputwriter,但如果您的商品位于列表中,那么可以制作另一个列表以排除值:

l = [-33.939999, 151.03918, '--', 'masked', 'masked']
x = ['masked','--']

content = (set(l)-set(x))

for item in content:
    outputwriter.writerow(item)
    print item

<强>输出:

151.03918
-33.939999