在迭代过程中使用奇数个项目在同一行上打印dict的值和下一个值

时间:2018-10-31 15:16:19

标签: python python-2.7 dictionary iteration

(Python 2.7)在我之前的问题中,我试图遍历字典“ rooms”的键,并且每行仅显示两个键,如何才能一次显示奇数个房间?更具体地说,每行两行,直到只剩下一行,并且只有一行会自己行。

Previous Question

当前代码:

rooms = {
"101": "Classroom",
"102": "Bathroom",
"103": "Room",
"104": "Room",
"105": "Room",
"106": "Room"}


keys = iter(sorted(rooms.keys()))
for key in keys:
    print key + "    " + next(keys)

当前输出:

101    102
103    104
105    106

目标输出:

101    102
103    104
105    106
107

3 个答案:

答案 0 :(得分:1)

next()使用可选的第二个参数作为默认值,以在迭代器用尽时返回。

keys = iter(sorted(rooms.keys()))
for key in keys:
    print key + "    " + next(keys, "")

答案 1 :(得分:0)

rooms = {
"101": "Classroom",
"102": "Bathroom",
"103": "Room",
"104": "Room",
"105": "Room",
"106": "Room",
"107": "Room"}


keys = iter(sorted(rooms.keys()))
for key in keys:
    try:
        print(key + "    " + next(keys))
    except StopIteration:
        print(key)

尽管将keys设为列表,然后检查是否到达末尾要简单得多。

答案 2 :(得分:0)

或者使用enumerate

from __future__ import print_function

per_line = 2
keys = iter(sorted(rooms.keys()))
for i, key in enumerate(keys):
    if (i + 1) % per_line == 0 or (i + 1) == len(rooms.keys()):
        print(key)
    else:
        print(key, end="\t")