python - 在 python 中打印列表输出的最佳方法

标签 python list

我有一个 list和一个 list of list像这样

>>> list2 = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"]]
>>> list1 = ["a","b","c"]

我压缩了上面的两个列表,以便我可以按索引匹配它们的值。

>>> mylist = zip(list1,list2)
>>> mylist
[('a', ['1', '2', '3', '4']), ('b', ['5', '6', '7', '8']), ('c', ['9', '10', '11', '12'])]

现在我尝试打印上面 mylist 的输出使用

>>> for item in mylist:
...     print item[0]
...     print "---".join(item[1])
...

它导致了这个输出,这是我的 desired output .

a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

现在,我的问题是还有一个 cleaner and better实现我想要的输出的方法或者这是 best(short and more readable)可能的方式。

最佳答案

好吧,你可以避免使用一些临时变量并使用更好的循环:

for label, vals in zip(list1, list2):
    print label
    print '---'.join(vals)

不过,我认为您不会从根本上获得任何“更好”的东西。

关于python - 在 python 中打印列表输出的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760019/

相关文章:

python - 将服装二进制数据文件读入 pandas 数据帧

python - 从 NLTK.tree 结果中获取实体

python - 更改从 *.csv 文件读取的数据

c# - 尝试将对象添加到类中的列表时出现 "Object reference not set to an instance of an object"错误

list - 如何在 NetLogo 中创建一个包含从 1 到给定数字的数字的列表?

python - 调用函数时将列表转换为 *args

Python:参数没有正确传递给命令

python - 如何在 MacOS 上将 Python 2.x 升级到最新的 2.x 版本

python - 将列表传递给函数以充当多个参数

r - 计算列表中的值