删除词典列表中的'inner'列表

  • 本文关键字:列表 inner 删除 python json
  • 更新时间 :
  • 英文 :


我最近正在使用pokeapi,并试图从中筛选出一些值。我正在处理的JSON是这样的:https://pokeapi.co/api/v2/pokemon/golduck/.

我需要的是,当level_learned_at字典键的值为0时,或者当move_learn_method未升级时,找到一种方法来删除大列表[移动]中的列表"version_group_details"。然后用这些信息创建一个新的列表,只使用那些特定的键和值。

我在这里的重点是获得一个干净的字典列表,其中包含级别提升值高于0的移动。(我正在试着制作一张只有通过升级才能学到的能力的小桌子(。

如有任何帮助,我们将不胜感激!

使用我现在拥有的代码进行编辑:

self.moves就是这样:https://pokeapi.co/api/v2/pokemon/golduck/



jsonfile = self.moves
move = jsonfile['moves']
lst = list(self.__evo_generator(move, 'move'))
return lst

这将是"获得"我能力的原因,下面是我调用的生成器:

def __evo_generatortwo(self):
req = request.Request(
self.moves,
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
}
)
with request.urlopen(req) as r:
data = loads(r.read())
moves = [
m['move']['name']
for m in data['moves']
if any(d['level_learned_at'] > 0 and d['move_learn_method']['name']=='level-up'
for d in m['version_group_details'])
]
print(moves)

UPDATED CODE
Up above I updated how the looks, although i am getting the following error: URLError
urllib.error.URLError: <urlopen error unknown url type: {'abilities'>
What could be the cause to this? Or did I make some mistakes when replacing the values with mine?
(I did go with the single list statement option since I don't feel confident enough to mess around with generators, haha)

如果你只需要任何可以通过升级学习的移动,在任何级别(0除外(,并且没有额外的限制:

from json import loads
from urllib import request
req = request.Request(
'https://pokeapi.co/api/v2/pokemon/golduck/',
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
}
)
with request.urlopen(req) as r:
data = loads(r.read())

def __evo_generator(moves):
for m in moves:
if any(d['level_learned_at'] > 0 and d['move_learn_method']['name']=='level-up' for d in m['version_group_details']):
yield m['move']['name']

for m in __evo_generator(data['moves']):
print(m)

请注意,我已经删除了self,因为您没有提供该类的其余代码,但您当然可以将该函数变成一个方法。由于密钥实际上是由两部分组成的("ve"one_answers"name"(,我把它省略了,但你可以把它加回来。

我把这个函数写成了生成器,因为这是你所走的路线,但你也可以在一条语句中得到移动的列表:

moves = [
m['move']['name']
for m in data['moves']
if any(d['level_learned_at'] > 0 and d['move_learn_method']['name']=='level-up'
for d in m['version_group_details'])
]
print(moves)

编辑:答案中的第一个代码示例旨在自行运行,但在原始代码中,您可能只需要__evo_generator生成器,或代码的第二位,而不是它。

最新更新