如何在Python中向列表添加字符串?

2024-05-16 21:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的值列表:

15,100,25.0
-50,-50,50.0
-20,120,70,40
200,-100,25,5

前两行表示圆的值,第三行表示矩形,第四行表示多边形。我希望输出如下:

c 15,100,25.0
c -50,-50,50.0
r -20,120,70,40
p 200,-100,25,5

我不知道怎样才能把每一行都加上这封信。我有一个for循环,用来遍历字符串中的信息来打印它们。

for shapes in list_of_shapes:
    print(",".join(str(item) for item in shapes))

以下是我的一些代码:

list_of_shapes = []

while p >= 0:

    #Here is a bunch of code

    list_of_shapes.append("c")
    list_of_shapes.append(circle) # appends the data for the circles
while p2 >= 0:
    #bunch of code
    list_of_shapes.append("r")
    list_of_shapes.append(rect) # appends the data for the rectangle
while p3 >= 0:
    #code
    list_of_shapes.append("p")
    list_of_shapes.append(poly) # appends the data for the polygon

    return list_of_shapes

一旦我为他们做了这些,我会得到:

c
15,100,25.0
c
-50,-50,50.0
r
-20,120,70,40
p
200,-100,25,5

任何帮助都将不胜感激:)


Tags: ofthein列表fordatacodeitem
3条回答

您所做的只是在列表中添加额外的字符串,而不是在字符串本身附加/前置。

从上面的代码中,如果您只需要一个字符串列表,您可能可以这样做:

list_of_shapes = []

while p >= 0:

    #Here is a bunch of code

    list_of_shapes.append("c {0}".format(','.join(circle))) # append data for circles by converting the circle list into a string
while p2 >= 0:
    #bunch of code
    list_of_shapes.append("r {0}".format(','.join(rect))) # append data for rect by converting the rect list into a string
while p3 >= 0:
    #code
    list_of_shapes.append("p {0}".format(','.join(poly))) # append data for polygon by converting the poly list into a string

return list_of_shapes

然后你可以这样打印这个列表:

for shape in list_of_shapes: print(shape)

注意,在所有的while块中,您现在只执行list_of_shapes.append一次。

这使用^{}允许您以特定方式格式化字符串。

但是,如果您希望单独保留所有列表数据(而不是将其全部设为字符串),像Snakes和Coffee建议的那样可以工作。

问题就在这里:

while p >= 0:

    #Here is a bunch of code

    list_of_shapes.append("c")
    list_of_shapes.append(circle) # appends the data for the circles
while p2 >= 0:
    #bunch of code
    list_of_shapes.append("r")
    list_of_shapes.append(rect) # appends the data for the rectangle
while p3 >= 0:
    #code
    list_of_shapes.append("p")
    list_of_shapes.append(poly) # appends the data for the polygon

    return list_of_shapes

这给了你['c', <circle>, 'r', <rect>, 'p', <poly>]。你可以这样做:

while p >= 0:

    #Here is a bunch of code
    list_of_shapes.append(("c", circle)) # appends the data for the circles
while p2 >= 0:
    #bunch of code
    list_of_shapes.append(("r", rect)) # appends the data for the rectangle
while p3 >= 0:
    #code
    list_of_shapes.append(("p", poly)) # appends the data for the polygon

    return list_of_shapes

这基本上是将每个形状与其分类配对。然后您可以通过执行以下操作进行打印:

for shape_type, shape in list_of_shapes:
    print("{} {}".format(shape_type, ",".join(str(item) for item in shapes)))

要将所需的信件附加到列表中,可以执行以下操作:

list = [15,100,25.0]
list_with_letter = ["c"] + list

相关问题 更多 >