开发者

Get the name of a list item

I have easy access 开发者_运维技巧to a list of variables as such:

[a, b, c,]

I was wondering, can you introspect (or something) on the variable names to get a dict that looks like this:

{ 'a'=a, 'b'=b, 'c'=c }


The list doesn't “contain variables”. It refers to the objects it contains; just as the names ‘a’, ‘b’, ‘c’ refer to those same objects.

So getting an item from the list gets you the object. That object may have zero, one, or many names; it doesn't know any of them.

If you know at the time you create the list that you will later want to refer to the items by name, then it sounds like you want to create a dict instead.


Something like below maybe?

dict(zip(arr,arr))

Edit:

From the suggested duplicates, if you want that:

for i in ('a', 'b', 'c'):
   dic[i] = locals()[i]

but you must have the list as ['a','b','c'] If you have it as [a,b,c] the values would have replaced the variable names anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜