繁体   English   中英

如何将文本和列表压缩为一行代码?

[英]How do I condense text and a list into one line of code?

我当前的代码如下所示:

list = ['A', 'B', 'C', 'D', 'E']

print("The first three items in the list are: ")

print(*list[0:3], sep=', ')

我想知道如何将两个打印件合并为一个打印件?

这应该工作

代码:

list = ['A', 'B', 'C', 'D', 'E']

print(f"The first three items in the list are: {', '.join(list[0:3])}")

输出:

The first three items in the list are: A, B, C

@sabil 和 @timroberts 的答案很好。 有时蛮力有其优势。 在这种情况下,打印语句可能会有点长。

mylist = ['A', 'B', 'C', 'D', 'E']
print(f'The first three items in the list are: {mylist[0]}, {mylist[1]}, and {mylist[2]}')

您还可以为 print 提供许多参数,它们都将被打印:

mylist = ['A', 'B', 'C', 'D', 'E']
print('The first three items in the list are: ', mylist[0], ',',
      mylist[1], ', and ', mylist[2])

请注意,我已将您的变量list重命名为mylist list是 Python 中的保留关键字,如果将其用作变量名,可能会遇到麻烦。 例如,稍后在您的代码中说您想使用list()函数将范围转换为列表。 它不起作用,因为list已经重新分配给变量。

mylist2 = list(range(4))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM