打印列表项python

2024-07-04 07:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有两个项目的清单,每一个项目都是一本字典。现在我想打印这个条目,但是由于这些都是dicts,python写的是dicts,而不是名称。有什么建议吗?在

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' )

Tags: 项目in名称for字典条目itemsep
2条回答

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

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')

正如您在this other question中看到的,不可能访问实例名称,除非您将dict子类化并将名称传递给自定义类的构造函数,以便您的自定义dict实例可以有一个您可以访问的名称。在

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

由于sep是一个存储dictionariesvariables的列表,当您试图打印sep时,您将打印{}。在

如果您真的需要将每个variablename打印为string,一种方法是同时创建另一个list,其中variable名称作为字符串:

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

然后你就可以完成剩下的代码了。在

相关问题 更多 >

    热门问题