我想打印None,但是不知何故它没有进入我准备的循环。
我的代码:
新更新:
a = [{"king":[{"tok":"many", "quite":"forget"}],"man":"one"},{"man":"one"},{"man":"onee"}, {"king":[{"tok":"sin"}]},{"king":[{"tok":"kingkong"}]}]
aa = ["many", "yet", "sin"]
for xx in aa:
for x in a:
exists = x.get('king', [])
if exists:
for e in exists:
if xx == e["tok"]:
print(xx)
else:
print("wrong")
else:
print("empty")
我当前的输出:
many
empty
empty
wrong
wrong
wrong
empty
empty
wrong
wrong
wrong
empty
empty
sin
wrong
预期输出:
many
empty
empty
sin
wrong
我不知道为什么它循环了这么多次却没有打印出预期的输出结果
答案 0 :(得分:0)
在我看来,您似乎只想检查列表中每个子字典中是否存在“国王”。在这种情况下,您可以直接检查该密钥。
a = [{"king":["man"],"man":"one"},{"man":"one"}]
for x in a:
exists = x.get('king', [])
if exists:
print 'has'
else:
print 'None'
输出:
has
None
更新-
如果国王存在,您似乎只想打印国王的属性。但是,仅当king具有'tok'属性时才要打印它。下面的逻辑应允许您这样做。
for x in a:
king_attributes = x.get('king', [])
if not king_attributes:
print 'empty' # if no king available
continue
for attributes in king_attributes:
if 'tok' not in attributes:
print 'wrong'
else:
print attributes['tok'] # print the tok if we have it
输出:
many
empty
empty
sin
kingkong