我想知道是否有“正确”或“首选”方法来使用列表实体打印消息。
我目前正在学习 Python 速成类(class) 2ed,练习 3-4 要求:
如果您可以邀请任何人(无论是在世的还是已故的)共进晚餐,您会邀请谁?列出至少包含三个您想邀请共进晚餐的人的列表。然后使用您的列表向每个人打印一条消息,邀请他们共进晚餐。
我编写的代码可以完成工作,但它与网上找到的解决方案不同。
我的代码:
guests = ['abe lincoln', 'jesus', 'jack nicholson']
print(f"Hello, {guests[0].title()}, would you like to come to dinner?")
print(f"Hello, {guests[1].title()}, would you like to come to dinner?")
print(f"Hello, {guests[2].title()}, would you like to come to dinner?")
书中的解决方案:
guests = ['guido van rossum', 'jack turner', 'lynn hill']
name = guests[0].title()
print(name + ", please come to dinner.")
name = guests[1].title()
print(name + ", please come to dinner.")
name = guests[2].title()
print(name + ", please come to dinner.")
它们都产生了所需的结果,但其中一种形式比另一种更好用吗?
最佳答案
当使用列表或其他可迭代类型时,最优选的循环方式,例如:
guests = ['abe lincoln', 'jesus', 'jack nicholson']
for i in range(len(guests)):
print(f"Hello, {guests[i].title()}, would you like to come to dinner?")
此外,在 Python 中,for 循环可以简单地用作:
for guest in guests:
print(f"Hello, {guest.title()}, would you like to come to dinner?")
一行:
for guest in guests : print(f"Hello, {guest.title()}, would you like to come to dinner?")
奖金:
print(f"{0}".format(argument))
也可用于以有序方式在 print 函数中传递参数。示例:
print(f"Hello, {0}, would you like to come to dinner?".format(guest.title()))
关于python - 是否有使用列表实体打印消息的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839996/