如何很好地打印出指定格式的元素列表?



我必须以指定格式打印出 2 个列表的元素。例如

list1 = ["a", "b", "c"]

list2 = ["1", "2", "3"]

我想打印出来像

"a: 1, b: 2, c: 3"

我可以写这样的代码,

print("{}: {}, {}: {}, {}: {}".format(list1[0], list2[0],  list1[1], list2[1],  list1[2], list2[2])  

但是 2 个列表的元素数量不确定,所以我想知道如何重复格式以打印出来。

如果两个序列的长度相同:

list1 = ["a", "b", "c"]
list2 = ["1", "2", "3"]
print(', '.join('{}: {}'.format(a, b) for a, b in zip(list1, list2)))

输出:

a: 1, b: 2, c: 3

在 Python 3.6+ 中,你可以使用 f 字符串来更简洁地做到这一点:

print(', '.join(f'{a}: {b}' for a, b in zip(list1, list2)))

您可以使用zip

for letter, number in zip(list1, list2):
print(f"{letter}: {number}")

这将起作用,但您可能还需要考虑使用字典:

my_dict = {"a": "1", "b": "2", "c": "3"}
print(my_dict)

最好的选择可能只是两者的结合:

print(dict(zip(list1, list2))

但这只有在list1list2大小相同时才有效

最新更新