如何在python中打印没有方括号的特定数组元素?

2024-04-20 02:34:29 发布

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

当我运行程序时,如何让第二个循环中的列表元素在没有方括号的情况下打印出来?你知道吗

room_lengths=[]
room_widths=[]
areas=[]
print("House floor area calculator")
rooms=int(input("How many rooms are there? "))
a=1
b=1
for x in range(rooms):
    print("How long (m) is Room ",a,"? ")
    length=float(input())
    print("How wide (m) is Room ",a,"? ")
    width=float(input())
    area=length*width
    room_lengths.append(length)
    room_widths.append(width)
    areas.append(area)
    a+=1
print("The total area is calculated as:")
for x in range (rooms):
    print("Room",b)
    ### Below line does not print as desired ###
    print(room_lengths[b-1:b],"x" ,room_widths[b-1:b],"=",areas[b-1:b],"m²")
    b+=1
total_area=sum(areas)
print("The total area is ,",total_area,"m²")

Tags: inputisareawidthlengthhowtotalroom
2条回答

使用str.format提取单个元素而不是切片数组:

print('{0} x {1} = {2} m²'.format(room_lengths[b-1], room_widths[b-1], areas[b-1]))

输出示例:

The total area is calculated as:
Room 1
10.0 x 20.0 = 200.0 m²
Room 2
30.0 x 40.0 = 1200.0 m²
for l, w, a in zip(room_lengths, room_widths, areas):
    print('{0} x {1} = {2} m²'.format(l, w, a))

相关问题 更多 >