有没有办法把这个循环缩短成一行?

2024-10-01 00:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

无论如何,这一行,但没有列表理解

for x in someDict["place"]:  # make this
    for thing in x:          # and this one line?
        print(x[thing]["this_des1"])
        print(x[thing]["that_des2"])
someDict = {
"place": [ { 0 : { "this_des1": 'data1', "that_des2" : 'data2' } },
           { 1 : { "this_ces1": 'data3', "that_ces2" : 'data4' } } ] }

Tags: andin列表formakethatlineplace
1条回答
网友
1楼 · 发布于 2024-10-01 00:27:39

由于您的dict有不同的键,而且似乎您正在尝试打印所有的底层值,因此使用values()比硬编码键更容易

>>> print('\n'.join(z for x in someDict["place"] for y in x.values() for z in y.values()))
data1
data2
data3
data4

相关问题 更多 >