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

Python列表格式转换:将[(0, 0), (1, 1)]转为{{0, 0}, {1, 1}}

Python列表转指定大括号格式的方法

你可以用以下几种方式将列表 [(0, 0), (1, 1)] 转换为 {{0, 0}, {1, 1}} 格式:

方法一:字符串替换法

这种方法操作简单,直接通过字符串替换完成格式转换:

original_list = [(0, 0), (1, 1)]
formatted_str = str(original_list).replace('[', '{').replace(']', '}').replace('(', '{').replace(')', '}')
print(formatted_str)  # 输出: {{0, 0}, {1, 1}}

原理是先把列表转为字符串,再将所有方括号、小括号统一替换为大括号。

方法二:生成式拼接法

这种方法更灵活,能精准控制每个元素的格式,避免意外替换问题:

original_list = [(0, 0), (1, 1)]
# 生成每个元组对应的"{x, y}"格式字符串
element_strs = [f"{{{x}, {y}}}" for x, y in original_list]
# 拼接成最终目标格式
formatted_str = f"{{{', '.join(element_strs)}}}"
print(formatted_str)  # 输出: {{0, 0}, {1, 1}}

先通过列表生成器处理每个元组,再利用字符串格式化拼接成最终格式。

内容的提问来源于stack exchange,提问作者41_ Andi Yuda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:25:18