简体   繁体   English

打印列表项-Python

[英]Print list items - python

I have a list with two item, each item is a dictionary. 我有一个包含两个项目的列表,每个项目都是一本字典。 now I want to print the item but as these are dicts, python writes the dicts and not the name. 现在我想打印项目,但由于这些是字典,因此python会写出字典而不是名称。 any suggestion? 有什么建议吗?

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

My suggestion is that you use a dict for sep, instead of a list. 我的建议是,对sep使用字典,而不是列表。 That way you could make the dict names as string-keys for them: 这样,您可以将字典名称作为它们的字符串键:

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

As you can see in this other question , it's impossible to access instance names, unless you subclass dict and pass a name to the constructor of your custom class, so that your custom dict instance can have a name that you can have access to. 正如您在另一个问题中看到的那样,除非您将dict子类化并将名称传递给自定义类的构造函数,否则无法访问实例名称,以便自定义dict实例可以具有可以访问的名称。

So in that case, I suggest that you use dicts with name-keys to store your dicts, instead of a list. 因此,在这种情况下,我建议您使用带名称键的字典来存储您的字典,而不是列表。

As sep is a list of variables storing the dictionaries , when you try to print sep you will print the dictionaries . 因为sep是存储dictionariesvariables的列表,所以当您尝试打印sep ,将打印dictionaries

If you really need to print each variable name as a string , one way to do that is this to also create an other list with the variable names as strings: 如果您确实需要将每个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

Then you can do the rest of your code. 然后,您可以完成其余的代码。

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

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