我尝试尽可能地压缩以下代码,并尽可能使用pythonic格式,谢谢建议。
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
import yaml
FILE='t'
with open(FILE, 'r') as F:
doc = yaml.load(F)
compr = [x for x in doc]
for x in doc:
for k,v in x.items():
print "\n"
print k
for k2,v2 in v.items():
print k2,
for b in v2:
print b,
doc的输出如下:
[{'UK': {'City': [1, 2, 3]}}, {'France': {'City': [1, 2]}}, {'US': {'City': [1, 2, 3]}}]
我的预期输出如下:
UK
City 1 2 3
France
City 1 2
US
City 1 2 3
答案 0 :(得分:1)
也许您可以尝试解包print
中的值,但是您可能需要按照其他answer中的说明为python2导入print_function
:
from __future__ import print_function
doc = [{'UK': {'City': [1, 2, 3]}}, {'France': {'City': [1, 2]}}, {'US': {'City': [1, 2, 3]}}]
for element in doc:
for k1, v1 in element.items():
print(k1)
print(*v1, ' '.join(map(str,*v1.values())), sep=' ')
答案 1 :(得分:0)
您可以尝试以下方法:
doc = [{'UK': {'City': [1, 2, 3]}}, {'France': {'City': [1, 2]}}, {'US': {'City': [1, 2, 3]}}]
for dic in doc:
for country, data in dic.items():
print(country)
for city, numbers in data.items():
print(' '.join([city] + list(map(str, numbers))))
哪个给:
UK
City 1 2 3
France
City 1 2
US
City 1 2 3