繁体   English   中英

打印列表项-Python

[英]Print list items - python

我有一个包含两个项目的列表,每个项目都是一本字典。 现在我想打印项目,但由于这些是字典,因此python会写出字典而不是名称。 有什么建议吗?

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}    
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = [sep_st, sep_dy]
for item in sep:
  for values in sorted(item.keys()): 
    p.write (str(item)) # here is where I want to write just the name of list element into a file 
    p.write (str(values))
    p.write (str(item[values]) +'\n' )

我的建议是,对sep使用字典,而不是列表。 这样,您可以将字典名称作为它们的字符串键:

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}    
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = {"sep_st": sep_st, "sep_dy": sep_dy} # dict instead of list
for item in sep:
  for values in sorted(sep[item].keys()): 
    p.write (str(item))
    p.write (str(values))
    p.write (str(sep[item][values]) +'\n')

正如您在另一个问题中看到的那样,除非您将dict子类化并将名称传递给自定义类的构造函数,否则无法访问实例名称,以便自定义dict实例可以具有可以访问的名称。

因此,在这种情况下,我建议您使用带名称键的字典来存储您的字典,而不是列表。

因为sep是存储dictionariesvariables的列表,所以当您尝试打印sep ,将打印dictionaries

如果您确实需要将每个variable 打印为string ,则一种方法是创建另一个以variable名作为字符串的list

sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}    
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = [sep_st, sep_dy]
sep_name = ['sep_st', 'sep_dy']
for i in sep_name:
    print i

然后,您可以完成其余的代码。

暂无
暂无

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

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