繁体   English   中英

Python:使用for循环水平打印字典内容

[英]Python: printing out contents of a dictionary horizontal with a for loop

我想水平打印字典的键,并在每第三个键上打印出一行。 我这样写:

fields= {1 : "not", 2 : "not", 3 : "not",
         4 : "not", 5 : "not", 6 : "not",
         7 : "not", 8 : "not", 9 : "not"} 
for i in fields:
print(i)
if i%3==0:
    print ("\n")

但是,输出只是水平的,每三个数字之间有两个换行符。

我想要的输出是这样的:

123

456

789

这是你想要的吗 ?

fields= {1 : "not", 2 : "not", 3 : "not",
         4 : "not", 5 : "not", 6 : "not",
         7 : "not", 8 : "not", 9 : "not"}
for Key,values in fields.items():
    print(Key, end = "")#python3 , if in python2 use print item, instead.
    if Key%3==0:
        print ("\n")


123

456

789

如果使用python 3,或为python 2导入打印功能,则可以指定print的end参数,例如: print(i, end="") ,并且字典键之间不会有换行符。 但是由于字典键没有顺序,因此将以“随机”顺序打印它们,以避免这种情况,列出键列表,然后在打印之前对其进行排序,如下所示: keys = sorted(dict.keys())

print (i),将为您解决问题。 附带说明,您的代码缩进不正确。

fields= {1 : "not", 2 : "not", 3 : "not",
         4 : "not", 5 : "not", 6 : "not",
         7 : "not", 8 : "not", 9 : "not"} 
for i in fields:
  print (i),
  if i%3==0:
    print ("\n")`

尽管解决方案适用于给定的情况,但我想向您解释一些事情。 python中的dictionary未排序。 在这种情况下,因为您只用简单的1,2,3...键进行声明的方式就很好了。 您可能会认为 dict是这样工作的。

>>> a = {1 : "not", 2 : "not", 3 : "not",4 : "not", 5 : "not", 6 : "not",7 : "not", 8 : "not", 9 : "not"}
>>> a
{1: 'not', 2: 'not', 3: 'not', 4: 'not', 5: 'not', 6: 'not', 7: 'not', 8: 'not', 9: 'not'}

好的,所以在这种情况下,所有解决方案都可以使用。 但是,如果您认为相同,并为以下dict尝试相同的代码

>>> a= {12 : "not", 21 : "not", 30 : "not",4 : "not", 15 : "not", 61 : "not",71 : "not", 8 : "not", 19 : "not"}

输出将不会以相同的顺序。

>>> a
{19: 'not', 4: 'not', 21: 'not', 71: 'not', 8: 'not', 12: 'not', 61: 'not', 30: 'not', 15: 'not'}

而且,如果您尝试对for keys in a:进行迭代和打印for keys in a:则会遇到很多问题。

因此,您想要所需的输出(字典没有排序,因此不可预测)请使用OrderedDict

from collections import OrderedDict
fields = [(1, 'not'), (2, 'not'), (3, 'not'),
          (4, 'not'), (5, 'not'), (6, 'not'),
          (7, 'not'), (8, 'not'), (9, 'not')]
a = OrderedDict(fields)
for i,key in enumerate(a):
    print(key,end='')
    i+=1
    if i%3==0:
        print()

输出:

123
456
789

还应使用enumerate()打印每三个值。 不要依靠钥匙。 如果您更改密钥怎么办?

i,enumerate(dictionary)的键只给出像这些0,key1 1,key2 2,key3等等的值。 仅给出数字对,仅此而已。

尝试更改键并使用此代码和其他代码,您会注意到对于此解决方案,更改结果的数量将相同。 而不是其他。 请记住,您的代码应始终具有适应性。 不应完全仅依赖于特定的输入集

123
456
789

请注意 ,如果您希望将它们分隔为换行符,则只有print()会这样做。 如果您想在两者之间使用空格(换行符),请使用`print(“ \\ n”)。

123

456

789

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM