我的代码:
msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']
counter = 0
for key, val in msgs.items():
while counter < len(val):
print(key, val[counter])
counter += 1
下面是我当前得到的输出:
ch1 testmsg1
ch1 testmsg2
ch2 testmsg5
下面是我想要的输出:
ch1 testmsg1
ch1 testmsg2
ch2 testmsg3
ch2 testmsg4
ch2 testmsg5
提前感谢您的帮助,我还在学习中,希望您能解释一下!
看起来您想要获取列表中的所有值。正如@ jneville所说,你可以修复你使用计数器的方式,但是既然你知道列表中有多少对象,你最好使用for循环而不是while循环。所以
msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']
for key, val in msgs.items():
for element in val:
print(key, element)
如果您想在这里使用while循环,则需要像这样将计数器变量移动到for循环中:
msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']
for key, val in msgs.items():
counter = 0
while counter < len(val):
print(key, val[counter])
counter += 1
这样,当计数器转到字典中的下一个键时,它将重置为0。之前,计数器在testmsg1
处为0,在testmsg2
处为1,但是当它遇到键ch2
时,计数器现在为2,并且只打印testmsg5
。
你能做到以下,还是我错过了什么?
msgs = {}
msgs['ch1']=['testmsg1', 'testmsg2']
msgs['ch2']=['testmsg3','testmsg4','testmsg5']
for key in msgs:
for val in msgs[key]:
print(key, val)
单次迭代:
- 创建一个字符串模板
- 使用
map
将模板应用于列表中的每个值 - 使用
print
和分隔符n
for k, vs in msgs.items():
template = k + ' {}'
print(*map(template.format, vs), sep='n')
或者使用简单的两行方式使用str.join
:
for k, vs in msgs.items():
print('n'.join(f'{k} {v}' for v in vs))