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

Python中如何将sep参数与sorted函数搭配使用

问题原因
  • 你调用print()时仅传入了1个参数:sorted(numbers)返回的完整列表对象,而sep参数的作用是分隔print()接收到的多个独立位置参数,仅传入1个参数时sep不会生效。
解决方案

有两种常见实现方式:

方法1:解包列表后传入print

用Python的解包运算符*把排序后的列表元素拆成多个独立参数传入print(),此时sep参数就会正常生效:

numbers = [3, 7, 5]
print(*sorted(numbers), sep="<")

运行后输出结果为3<5<7。

方法2:用join方法拼接后输出

如果需要把拼接后的结果存储为变量再使用,可以先把所有数字转成字符串,再调用字符串的join方法用指定分隔符拼接:

numbers = [3, 7, 5]
sorted_str = "<".join(str(num) for num in sorted(numbers))
print(sorted_str)

运行输出结果和方法1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:57:02