循环遍历轨道键并跳转到循环结构的相应部分



My repl

(适用于各种语言用例的各种 JSON 文件。

import json
# v = "64457.json" #jp
# v = "35777.json" #en, jp, ro
v = "66622.json" #ge, jp, ro
# v = "50900k.json" #ko
# v = "25364c.json" #ch, en
with open(v) as f:
data = json.load(f)
track_list = data['discs'][0]['tracks']
langs = ('German', 'French' , 'Korean', 'Chinese')
for x, track in enumerate(track_list):
for i in track['names']:
print i, len(track["names"].keys())
if i not in langs:
print "NOT I"
if len(track["names"].keys()) == 3 and i in ('Romaji', 'Japanese', 'English'):
d = track["names"]["Romaji"]
s = track["names"]["Japanese"]
y = track["names"]["English"]
print '-', x+1, y, d, s
break
elif len(track["names"].keys()) == 3 and i in langs and i in ('Romaji', 'Japanese'):
d = track["names"]["Romaji"]
s = track["names"]["Japanese"]
y = track["names"][i]
print '@', x+1, y, d, s
break
elif len(track["names"].keys()) == 2 and i in langs:
y = track["names"][i]
e = track["names"]["English"]
print '+', x+1, y, e
break
else:
print '~', x+1, track["names"].values()[0]

打印错误

German 3
Japanese 3
NOT I
Traceback (most recent call last):
File "main.py", line 25, in <module>
y = track["names"]["English"]
KeyError: 'English'

我想做什么

我正在尝试遍历track['names']中的每个键。一旦它命中也在langs元组中的键,我希望它停止并转到if部分中的相应部分。如果它不在langs元组中,它应该输出它确实拥有的信息,特别是如果键是 Eng、RomJpn。我认为所有的循环都让我感到困惑。

我不完全了解您关心哪些条件,但您可以修改以下代码以满足您的需求。你的 for 循环太多了,所以我取出了一个,然后设置了一些你可以使用的布尔变量。

track_list = data['discs'][0]['tracks']
langs = ('German', 'French' , 'Korean', 'Chinese')
for x, track in enumerate(track_list):
# below variable is an int with the number of names the track has
num_names = len(track["names"].keys())
# below variable is true if one of the track's names is in a lang language
name_in_lang_bool = any([lang in langs for lang in track["names"].keys()])
# below variable is true if one of the track's names is in Romaji or English
name_english_romaji_bool = any([lang in ("English", "Romaji") for lang in track["names"].keys()])
# you can combine these variables for various conditionals like so: 
if name_in_lang_bool and num_names == 3 and name_english_romaji_bool:
print "this track has three names, one of them is in langs, and one of them is either English OR Romaji"
# this is how you print out all the track's names: 
for (language, name) in track["names"].iteritems():
print "name in", language, "is", name
# here's another example condition 
elif name_in_lang_bool and num_names == 2:
print "this track has two names, one of them is in langs"
for (language, name) in track["names"].iteritems():
print "name in", language, "is", name

我认为看到一种完全不同的方法来解决问题可能会有所帮助:

  • 你在track["names"]中有键(我假设这是一本字典(
  • 然后你想要
    • 属于langs的键,以及
    • 不属于langs的密钥

考虑一下:

keys_in_langs = filter(lambda key: key in langs, track["names"].keys())
vice_versa = filter(lambda key: key not in langs, track["names"].keys())

filter将lambda函数应用于keys中的每个项目,返回该匿名函数返回true的列表。这是你需要的吗?

最新更新