📜  如何在python中并排打印两个列表(1)

📅  最后修改于: 2023-12-03 14:52:50.157000             🧑  作者: Mango

如何在 Python 中并排打印两个列表

在 Python 中,有时我们需要将两个列表进行并排打印,以方便查看和比较。本文将介绍三种不同的方法来实现这个目标。

方法一:使用 zip 函数

使用 Python 内置函数 zip,我们可以将两个列表的元素配对,然后通过 for 循环进行遍历,最终实现并排打印的效果。

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']

for item1, item2 in zip(list1, list2):
    print('{:<5}{:<5}'.format(item1, item2))

输出:

1    a    
2    b    
3    c    
4    d    
5    e    

可将 {:<5} 替换为其他格式化字符串,以调整对齐方式。

方法二:使用 pandas 库

如果我们需要对列表进行更加复杂的操作,例如添加表头、对齐打印等,使用 pandas 库将更为方便。

import pandas as pd

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']

df = pd.DataFrame({'List1': list1, 'List2': list2})
print(df)

输出:

   List1 List2
0      1     a
1      2     b
2      3     c
3      4     d
4      5     e
方法三:使用 tabulate 库

tabulate 库是一个用于将表格格式化输出的 Python 库。通过安装该库,我们可以使用以下代码实现并排打印效果。

from tabulate import tabulate

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']
table = [[i, j] for i, j in zip(list1, list2)]

print(tabulate(table, headers=['List1', 'List2']))

输出:

  List1    List2
-------  -------
      1  a
      2  b
      3  c
      4  d
      5  e

以上就是三种不同的方法来实现 Python 中两个列表的并排打印。可以根据实际需求,选择使用其中的一种或多种方法。