我有一个Python字典,其中列出了为该值定义的列表。我无法以我需要的格式打印输出。
dict = {1 : [2,3], 2 : [1,4], 3 : [2,4], 4 : [2,3]}
需要的打印格式:
1 - 2, 1 - 3
2 - 1, 2 - 4
3 - 2, 3 - 4
4 - 2, 4 - 3
代码:
dict = {1 : [2,3], 2 : [1,4], 3 : [2,4], 4 : [2,3]}
for key, value in sorted(dict.items()):
for links in value:
print ("{} - {},".format(key, links)),
输出:
1 - 2, 1 - 3, 2 - 1, 2 - 4, 3 - 2, 3 - 4, 4 - 2, 4 - 3,
或者:
for key, value in sorted(dict.items()):
for links in value:
print ("{} - {},".format(key, links))
1 - 2,
1 - 3,
2 - 1,
2 - 4,
3 - 2,
3 - 4,
4 - 2,
4 - 3,
答案 0 :(得分:2)
for key, value in sorted(dict.items()):
print ', '.join(("{} - {}".format(key, links)) for links in value)
答案 1 :(得分:0)
dictionary = {1: [2, 3], 2: [1, 4], 3: [2, 4], 4: [2, 3]}
for key, links in sorted(dictionary.items()):
print("{key} - {}, {key} - {}".format(*links, key=key))
答案 2 :(得分:0)
>>> for key, value in sorted(d.items()):
print('{} - {}, {} - {}'.format(key, value[0], key, value[1]))
1 - 2, 1 - 3
2 - 1, 2 - 4
3 - 2, 3 - 4
4 - 2, 4 - 3
>>>