逐行打印列表元素 - 是否可以使用格式 [英] print list elements line by line - is it possible using format

查看:38
本文介绍了逐行打印列表元素 - 是否可以使用格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢使用 .format()

是否可以使用它逐行打印元素.假设当然元素数量未知.

Is it possible using it to print element line by line. Assuming of course number of elements is unknown.

工作示例将不胜感激.

推荐答案

您可以在任何类型的字符串上使用字符串格式化程序,包括多行字符串.因此,当然,如果您有一个格式字符串 '{}\n{}\n{}',您可以将三个项目传递给它,并且它们都将放在不同的行上.

You can use the string formatter on really any kind of string, including multi-line string. So of course, if you had a format string '{}\n{}\n{}' you could pass three items to it, and they would be all placed on separate lines.

因此,对于您想要打印的动态数量的元素,您需要做的就是确保格式字符串也包含相同数量的格式项.解决此问题的一种方法是动态构造格式字符串.例如这个:

So with a dynamic number of elements you want to print, all you need to do is make sure that the format string contains the same number of format items too. One way to solve this would be to construct the format string dynamically. For example this:

'\n'.join('{}' for _ in range(len(my_list))).format(*my_list)

因此,您实际上首先创建了一个格式字符串,方法是让生成器为 my_list 中的每个元素生成一个格式项 {},并使用换行符将它们连接起来.所以结果字符串看起来像这样:{}\n{}\n...\n{}\n{}.

So you essentially create a format string first, by having a generator produce one format item {} per element in my_list, and joining these using a newline character. So the resulting string looks something like this: {}\n{}\n…\n{}\n{}.

然后您使用该字符串作为格式字符串,并对其调用 format,将解压缩的列表作为参数传递给它.所以你正确地填充了格式字符串的所有位置.

And then you use that string as the format string, and call format on it, passing the unpacked list as arguments to it. So you are correctly filling all spots of the format string.

所以,你可以做到这一点.然而,这并不是一个实际的想法.它看起来相当混乱,并不能很好地传达您的意图.更好的方法是分别处理列表中的每个项目并单独格式化,然后仅然后将它们连接在一起:

So, you can do it. However, this is not really a practical idea. It looks rather confusing and does not convey your intention well. A better way would be to handle each item of your list separately and format it separately, and only then join them together:

'\n'.join('{}'.format(item) for item in my_list)

至于只是逐行打印元素,当然,更明显的方法是不需要您构建一个带换行符的长字符串,而是遍历项目并逐行打印 -一:

As for just printing elements line by line, of course, the more obvious way, that wouldn’t require you to build one long string with line breaks, would be to loop over the items and just print them one-by-one:

for item in my_list:
    print(item)

    # or use string formatting for the item here
    print('{}'.format(item))

当然,正如thefourtheye所建议的,如果每次循环迭代都非常简单,您也可以将整个列表传递给print函数,并设置sep='\n'来打印元素每个都在单独的行上.

And of course, as thefourtheye suggested, if each loop iteration is very simple, you can also pass the whole list to the print function, and set sep='\n' to print the elements on separate lines each.

这篇关于逐行打印列表元素 - 是否可以使用格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆