打印清单显示单引号 [英] Printing list shows single quote mark

查看:78
本文介绍了打印清单显示单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下python代码段:

I have the following python code snippet:

LL=[]
for i in range(3):
    LL.append("a"+str(i))
print LL

输出为:

['a0', 'a1', 'a2']

如何打印为(使用print LL):

[a0, a1, a2]

即没有引号? 如果我使用以下代码:

i.e. without the quote mark? If I use the following code:

print "[",
for i in range (len(LL)-1):
    print LL[i] + ", ",
print LL[i+1]+"]"

这将打印[a0, a1, a2]

推荐答案

以下是对我有用的一个实用函数:

Here's one utility function that worked for me:

def printList(L):
    # print list of objects using string representation
    if (len(L) == 0):
        print "[]"
        return
    s = "["
    for i in range (len(L)-1):
        s += str(L[i]) + ", "
    s += str(L[i+1]) + "]"
    print s

例如,如果我们具有如下所示的点类,则可以用于任何对象的列表.

This works ok for list of any object, for example, if we have a point class as below:

class Point:
    def __init__(self, x_crd, y_crd):
        self.x = x_crd
        self.y = y_crd
    def __str__(self):
        return "(" + str(self.x) + "," + str(self.y) + ")"

并具有Point对象的列表:

And have a list of Point objects:

L = []
for i in range(5):
    L.append(Point(i,i))
printList(L)

输出为:

[(0,0), (1,1), (2,2), (3,3), (4,4)]

而且,它达到了我的目的. 谢谢.

And, it served my purpose. Thanks.

这篇关于打印清单显示单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆