如何在lis中创建新行

2024-09-28 01:33:30 发布

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

我正在使用记录和列表尝试这个简单的收据代码,在不同的客户之间我希望有一个新行,但因为它在列表中\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)

当你查看列表时,客户之间应该有一个间隙


Tags: 代码fromimport列表客户记录customerdetails
2条回答

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

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

可以使用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)

相关问题 更多 >

    热门问题