我有一个如下所示的值列表:
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
非常感谢任何帮助:)
答案 0 :(得分:4)
你正在做的只是在列表中添加额外的字符串,而不是在字符串本身附加/前置。
从上面的代码中,如果你只想要一个字符串列表,你可能会这样做:
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
。
这使用str.format()
,它允许您以特定方式格式化字符串。
但是,如果你想单独保留所有的列表数据(而不是完全是一个字符串),那么像Snakes和Coffee建议的那样就可以了。
答案 1 :(得分:2)
问题在于:
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)))
答案 2 :(得分:0)
要将您想要的信件附加到列表,您可以执行以下操作:
list = [15,100,25.0]
list_with_letter = ["c"] + list