我怎么能做到这一点,以使一个值变为“ null”如果有例外?
我正在存储来自API的数据(然后将其存储为泡菜),有时由于缺少字段而出现错误。我想知道如何做到这一点,以便它仅针对有问题的变量并将其值记录为“ null”。
问题是我要存储6个不同的变量,因此,如果其中一个有问题,则所有其他5个变量将被跳过。相反,我希望(或那些)有问题的变量被值“ null”(或无)代替。
meta = loaded_from_pickle('mydata.pickle'),
def getAllData():
data = []
for i in range(len(meta)):
try:
name = meta[i]['base']['name']
weight = meta[i]['base']['weight']
height = meta[i]['base']['height']
age = meta[i]['secondary']['age']
eye_color = meta[i]['secondary']['eye_color']
birthday = meta[i]['secondary']['birthday']
data.append((name, weight, height, age, eye_color, birthday))
except:
pass
return data
print(getAllData())
所以发生的事情是我最终丢失了很多数据点,因为某些数据没有“ eiye_color”或什么。因此,当有“除了”之外,我应该做的是“使有问题的变量=” null“”,而不仅仅是传递整个循环。
I'm storing data from an API (that I then store as a pickle) and sometimes there are errors due to missing fields. I'm wondering how I can make it so that it only targets the problematic variable and logs its value as "NULL".
The issue is that I'm storing 6 different variables, so if a single one of them has an issue, all other 5 variables will be skipped. Instead, I want that (or those) problematic variables get replaced by the value "NULL" (or None).
meta = loaded_from_pickle('myData.pickle')
def getAllData():
data = []
for i in range(len(meta)):
try:
name = meta[i]['base']['name']
weight = meta[i]['base']['weight']
height = meta[i]['base']['height']
age = meta[i]['secondary']['age']
eye_color = meta[i]['secondary']['eye_color']
birthday = meta[i]['secondary']['birthday']
data.append((name, weight, height, age, eye_color, birthday))
except:
pass
return data
print(getAllData())
So what happens is that I end up losing a lot of data points because some data doesn't have "eye_color" or whatnot. So what I should do when there's an "except" should be "make problematic variable = "NULL" ", rather than just passing the entire loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是使用Square括号直接访问键,请尝试使用
get()
而返回none
的默认值,如果找不到键。有关更多信息,请参见此答案 https://stackoverflow.com/a/1041421/3125312
您可以在代码中使用它:
您还可以使用
枚举
假设Meta是列表Instead of accessing the keys directly using square brackets try using
get()
it returns a default value ofNone
if the key is not found.See this answer for more info https://stackoverflow.com/a/11041421/3125312
You could use it in your code:
You could also rewrite your for loop using
enumerate
assuming meta is a list