猿问

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

我必须以指定格式打印出 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个列表的元素数量是不确定的,所以我想知道如何重复格式才能打印出来。


德玛西亚99
浏览 164回答 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))但这只有在大小相同时才list1有效list2
随时随地看视频慕课网APP

相关分类

Python
我要回答