从 python 中的元组中删除/替换错误 [英] Remove/Replace Error from Tuple in python

查看:37
本文介绍了从 python 中的元组中删除/替换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一串元组

LL =  [ ("text1",2,3,N/A), ("text2",N/A,5,6),("text3",N/A,5,N/A) ]

我需要

LL =  [ ("text1",2,3,-1), ("text2",-1,5,6), ("text2",-1,5,-1) ]

所以只需删除 N/A 替换为 -1.我需要阅读所有行吗?数据下载显示 N/A,它不是一个变量.

So simply remove N/A replace with -1. Do I need to read all lines? Data download shows N/A, its not a variable.

LL 是字符串

使用 ("text2",N/A,5,6).在 [0] 上运行 python 类型是str".在 [1] 上运行 python 类型,我没有输出.

Using ("text2",N/A,5,6). Running python type on [0] is 'str'. Running python type on [1] , i get no output.

如果我将上面的行拆分为 a、b、c、d,由于我想要数字而不是 N/A,有没有办法说如果不是数字替换为数字(-1).拆分每一行时.或者,如果错误替换为 -1.

If I split the line above as a, b,c,d, Since I want number not a N/A, is there a way to say if not number replace with a number (-1). WHILE SPLITTING each line. Or, if error replace with -1.

这是另一个有同样问题的链接,注意 [1] 有一个 N/A.http://download.finance.yahoo.com/d/quotes.csv?s=GS&f=sb6vt1&e=.csv

Here is another link with the same problem, notice [1] has a N/A. http://download.finance.yahoo.com/d/quotes.csv?s=GS&f=sb6vt1&e=.csv

在使用脾气暴躁的 CSV 字段进行数据下载后挣扎.如何使用 try/Except 格式.

After struggling with data download with ill tempered CSV fields. How could use try/Except format.

try: 
   IF XXX or YYY or ZZZ or AAA == 'N/A',
   (dont process data...skip to except and pass)
except:
   pass 

推荐答案

您下载的来源是一个 csv 文件,而不是一些奇怪的 Python 类型的东西.通过使用 CSV 模块,您可以更直接、更轻松地处理 CSV,而不是被黑客入侵一起解决.

The source you're downloading from is a csv file, not some weird python typle thing. You can handle CSVs more directly and easily by using the CSV module instead of you're hacked together solution.

import csv, urllib
rawStockInfo = csv.reader(urllib.urlopen('http://download.finance.yahoo.com/d/quotes.csv?s=GS+AAPL+MSFT+AMZN&f=sb6vt1&e=.csv'))
stocks = [] #list for our cleaned up version
for stock in rawStockInfo:
    print stock
    #this replaces the string "N/A" with the int -1
    stockClean = [-1 if x == 'N/A' else x for x in stock]
    stocks.append(stockClean)
print stocks

请注意,您可能希望将该列表表达式更改为在 stock 中的单元格上的另一个循环...这将尝试将任何字符串转换为整数,并将N/A"替换为-1.

Note that you may want to change that list expression into another loop over the cells in stock... This would try to convert any strings to integers, and also replace 'N/A' with -1.

stockClean = []
for cell in stock:
    try:
        stockClean.append(int(cell)) #turn the string '4' into the integer 4
    except ValueError:
        if cell == 'N/A':
            stockClean.append(-1)
        else:
            stockClean.append(cell)

这篇关于从 python 中的元组中删除/替换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆