[英]Python print flexible amount of lists side by side vertically
I'm new to python and trying to print a few lists side by side vertically eg list_1 = [1,2,3]
and list_2 = [4,5]
: 我是python的新手,尝试垂直并排打印一些列表,例如
list_1 = [1,2,3]
和list_2 = [4,5]
:
Output: 输出:
1 4
2 5
3 None
I found that map(None, list_1, list_2)
can achieve this. 我发现
map(None, list_1, list_2)
可以实现此目的。
However, I may have up to >10 lists to print vertically. 但是,我最多可以有10个以上的列表可以垂直打印。 I wonder if there is some neat way to do this.
我想知道是否有某种巧妙的方法可以做到这一点。
You could use map(None, list_1, list_2, list_3, ...)
, since map
can take an arbitrary number of arguments. 您可以使用
map(None, list_1, list_2, list_3, ...)
,因为map
可以接受任意数量的参数。
However, it is usually not a good idea to have numbered variable names. 但是,对变量名进行编号通常不是一个好主意。 It is often a sign that you should be using a
list
or tuple
instead. 这通常表明您应该使用
list
或tuple
。 So instead of having variables list_1
, ..., list_10
, you should have one variable columns
which is a list of lists. 因此不是变量
list_1
,..., list_10
,你应该有一个变量columns
是列表的列表。
If columns = [list_1, list_2]
, then 如果
columns = [list_1, list_2]
,则
import itertools as IT
rows = IT.izip_longest(*columns)
is equivalent to map(None, list_1, list_2)
and is compatible with Python3, which removes the map(None, ...)
option. 与
map(None, list_1, list_2)
等效,并且与Python3兼容,后者删除了map(None, ...)
选项。 Notice that this notation generalizes well to arbitrary number of lists without requiring you to type all those variable names by hand. 注意,这种表示法可以很好地概括为任意数量的列表,而无需您手动键入所有这些变量名。
The *
in IT.izip_longest(*columns, ...)
is Python's unpacking operator . 在
*
在IT.izip_longest(*columns, ...)
是Python的拆包操作 。 It unpacks the items in columns
and sends those items to IT.izip
as individual arguments. 它解压缩
columns
的项目并将这些项目作为单独的参数发送到IT.izip
。 This notation allows you to send an arbitrary number of arguments to a function. 该符号使您可以向函数发送任意数量的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.