我有一个如下所示的值列表:
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
任何帮助都将不胜感激:)
您所做的只是在列表中添加额外的字符串,而不是在字符串本身附加/前置。
从上面的代码中,如果您只需要一个字符串列表,您可能可以这样做:
然后你可以这样打印这个列表:
注意,在所有的
while
块中,您现在只执行list_of_shapes.append
一次。这使用^{} 允许您以特定方式格式化字符串。
但是,如果您希望单独保留所有列表数据(而不是将其全部设为字符串),像Snakes和Coffee建议的那样可以工作。
问题就在这里:
这给了你
['c', <circle>, 'r', <rect>, 'p', <poly>]
。你可以这样做:这基本上是将每个形状与其分类配对。然后您可以通过执行以下操作进行打印:
要将所需的信件附加到列表中,可以执行以下操作:
相关问题 更多 >
编程相关推荐