(Python 2.7)在我之前的问题中,我试图遍历字典“ rooms”的键,并且每行仅显示两个键,如何才能一次显示奇数个房间?更具体地说,每行两行,直到只剩下一行,并且只有一行会自己行。
当前代码:
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
答案 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")