Python 创建一个列表,将空值替换为同一索引中不同列表中的值

Python 创建一个列表,将空值替换为同一索引中不同列表中的值,python,Python,我查询一个api: url = 'https://api.forecast.io/forecast/'+api_key+'/'+lat+','+lng f = urllib2.urlopen(url) json_string = f.read() parsed_json = json.loads(json_string) c = parsed_json['currently'] 某些键已定义,而其他键未定义: if 'temperature' in c: 我想构建一个具有几个特定值的对象:

我查询一个api:

url = 'https://api.forecast.io/forecast/'+api_key+'/'+lat+','+lng
f = urllib2.urlopen(url)
json_string = f.read()
parsed_json = json.loads(json_string)
c = parsed_json['currently']
某些键已定义,而其他键未定义:

if 'temperature' in c: 
我想构建一个具有几个特定值的对象:

vector = [c['temperature'], ... c['wind_speed']
总共应该有11项。如果一个键未定义,我想用相同的索引替换另一个列表中该位置的值

averages = [average_temp, ... average_wind]
大概是这样的:

# for each of the keys I want:
   # if it is defined:
      # add this value to the list
   # else:
      # add the value at the same index in the averages vector

我想你可能会同时通过两个向量建立索引。当然,第一个向量尚未定义。无论如何,这些值需要首先被索引。什么是python式的方法呢?

每当你的问题包括“…来自同一索引的不同列表”,这就是一个例子
zip
获取一对列表,并将其转换为一对列表

然后,你需要一个左边的表达式,除非它是空的,在这种情况下是右边的

然后你用一种理解力把它映射到整个拉链上

因此:


(我不知道你的“null”是什么意思,也不知道你是如何检查的,但只要用
a不是无
不是a.is_null()
或任何适当的东西来替换
a!=null

你知道
dict.get()
?如果您希望在dict()中而不是列表中定义默认值,请参见以下答案:
[a if a != null else b for a, b in zip(A, B)]