【问题标题】:How to format output when vals are lists?当 val 是列表时如何格式化输出?
【发布时间】:2023-04-06 00:04:02
【问题描述】:

在下面的示例中,我想:

  • 在每个新键后添加一个空行,以使输出更易于阅读
  • 按字母顺序放置键(因此键按字母顺序排列,然后每个键的值按字母顺序排列)

最pythonic的方法是什么?

超级基础的例子:

wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}

for clothes, colors in wardrobe.items():
    for color in sorted(colors):
        print("{} {}".format(color, clothes))

输出:

blue shirt
red shirt
white shirt
black jeans
blue jeans

【问题讨论】:

  • 你的代码有效吗?
  • 按原样工作,它对值进行排序。它不会首先对键进行排序(或者根本不会)。它不会在每个键的最后一个实例之后留下换行符。

标签: python sorting dictionary formatting


【解决方案1】:

你可以使用f-strings -

wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}

for clothes in wardrobe: # .items is not unpythonic, but I do not like to use it

    for color in sorted(wardrobe[clothes]): # This may seem long, but it keeps track of things

        print(f'{color} {clothes}') # Use f-string

你可以使用.items,但我没有。所以,如果你觉得没问题,你可以使用.items

或列表理解(我不推荐这样做,因为无论如何我们都不会在这里“构建”列表)-

print(*[f'{color} {clothes}' for clothes in wardrobe for color in sorted(wardrobe[clothes])],sep='\n')

【讨论】:

  • F-string - 是的。但是您的代码不会按字母顺序排列,然后按值排序,并且不会在两个键之间添加空行。
  • 我不明白 alphabetize 的关键。你可以解释吗?我认为也许您想根据键对其进行排序
  • 是的,就是这样 - 输出将首先按字母排序,然后按与每个键关联的每个值。 _____ 牛仔裤应该在 _______ 衬衫之前。我能够对值进行排序,但不能对键进行排序。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 2011-08-21
  • 2016-12-26
  • 1970-01-01
相关资源
最近更新 更多