python - 是否有使用列表实体打印消息的正确方法?

标签 python python-3.x

我想知道是否有“正确”或“首选”方法来使用列表实体打印消息。

我目前正在学习 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/

相关文章:

javascript - flask.abort() 究竟做了什么?

Python - 如何将 IF 语句转换为函数以使用其他字符串多次调用?

regex - 有条件替换 pandas df 中的数字

python - 计算矩阵列平均值

没有其他日期字段的 Django TruncHour

python - 反转列表中的项目

python - 继承问题和 "self"引用

python - 使用 PyCLIPS 加载事实非常慢,而使用 CLIPS 加载速度很快

python - Python 中的并行启动进程串行执行?

python - 如何将列表的一部分传递给不同的变量?