如何在列表中换行

问题描述 投票:0回答:2

我正在尝试使用记录和列表以及在不同客户之间的这个简单的收据代码,我希望有一个新行,但是因为它在列表\n中不起作用。

我已经尝试将\n添加到代码的各个部分,并尝试添加print("\n"),但这也不起作用。

from collections import *

customer_details = namedtuple("Customer","ID First_Name  Surname Age Gender Product Price")

cus1 = customer_details(16785, "John","Apleased",36,"Male","coffee",70)

customers = [cus1]

cus2 = customer_details(10, "Steve","Jobs",67,"male","tea",40)

customers.append(cus2)

print(customers)

查看列表时,客户之间应该有空隙。

python python-3.x list
2个回答
0
投票

您可以使用join方法在新行中打印每个元素

print("\n".join(customers))

0
投票

您可以使用for循环

>>> for customer in customers:
...     print(customer)
... 
Customer(ID=16785, First_Name='John', Surname='Apleased', Age=36, Gender='Male', Product='coffee', Price=70)
Customer(ID=10, First_Name='Steve', Surname='Jobs', Age=67, Gender='male', Product='tea', Price=40)

或者您可以使用'\n'.join(),但是首先需要将customersnamedtuple的列表转换为字符串列表

>>> print('\n'.join(str(customer) for customer in customers))
Customer(ID=16785, First_Name='John', Surname='Apleased', Age=36, Gender='Male', Product='coffee', Price=70)
Customer(ID=10, First_Name='Steve', Surname='Jobs', Age=67, Gender='male', Product='tea', Price=40)
© www.soinside.com 2019 - 2024. All rights reserved.