You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用orderby库:如何在for循环中打印排序后的列表

问题分析与解决方案

Let me break down what's going wrong here and walk you through the fixes:

核心问题:你在遍历JSON字符串,不是排序后的列表

When you run json.dumps(sorted(dic, key=asc('BAIRRO').asc('RUA')), indent=2), it converts your sorted list into a formatted JSON string. So when you put that directly into a for loop, you're iterating over individual characters of the string—not the original list items you intended. That's why it's not working as expected.

正确的做法:先保留排序后的列表,再操作

Here's how to fix this step by step:

  1. Store the sorted list first
    Capture the sorted result in a variable before converting it to JSON:

    sorted_list = sorted(dic, key=asc('BAIRRO').asc('RUA'))
    
  2. Iterate over the list directly
    Now you can loop through the actual list items:

    for item in sorted_list:
        # Print each item as formatted JSON
        print(json.dumps(item, indent=2))
        # Or just print the item directly if you don't need JSON formatting
        # print(item)
    

列表推导式的用法(如果需要预处理)

If you want to pre-generate formatted JSON strings for all items first, you can use a list comprehension:

sorted_list = sorted(dic, key=asc('BAIRRO').asc('RUA'))
formatted_json_items = [json.dumps(item, indent=2) for item in sorted_list]

# Then iterate and print
for json_str in formatted_json_items:
    print(json_str)

为什么你的初始print语句 worked?

The original print(json.dumps(...)) worked because you were printing the entire JSON string (which represents the sorted list) as a single unit. The indent=2 just made it human-readable, but it was still one big string under the hood.

内容的提问来源于stack exchange,提问作者Shinomoto Asakura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:30:09