【问题标题】:How can I print this format in the list of python如何在 python 列表中打印这种格式
【发布时间】:2015-12-01 05:22:44
【问题描述】:

假设我在 python 中有这个列表

A = ["(a,1)", "(b,2)", "(c,3)", "(d,4)"]

那么我怎样才能以以下格式打印出来:

(a,1), (b,2), (c,3), (d,4)

使用一行,最好不使用for循环 提前致谢

【问题讨论】:

  • 有什么尝试吗?你知道ast.literal_eval?

标签: python list printing


【解决方案1】:

当 A 是 str 的列表时:

print(', '.join(A))

或更笼统地说:

print(', '.join(map(str, A)))

【讨论】:

    【解决方案2】:

    在您的情况下,下面的代码将起作用

    print(', '.join(A))
    

    【讨论】:

      【解决方案3】:

      你也可以使用正则表达式:

      >>> A = ["(a,1)", "(b,2)", "(c,3)", "(d,4)"]
      >>> import re
      >>> re.sub(r'[\[\]\"]', r"",",".join(A))
      '(a,1),(b,2),(c,3),(d,4)'
      

      【讨论】:

        猜你喜欢
        • 2015-06-09
        • 2022-07-11
        • 1970-01-01
        • 1970-01-01
        • 2011-11-13
        • 2021-12-31
        • 2013-10-24
        • 2016-10-16
        • 1970-01-01
        相关资源
        最近更新 更多