开发者

How to create a List given a variable "x" in Python?

开发者 https://www.devze.com 2023-01-25 21:17 出处:网络
Python: I have a variabl开发者_开发知识库e say x. I need to create a list of name \"x\"Use a dict.

Python:

I have a variabl开发者_开发知识库e say x. I need to create a list of name "x"


Use a dict.

mylists = {}

x = 'abhishek'
mylists[x] = []

That way, in mylists you'll have all your lists. mylists[x] is the list with name x.


Then just do it:

>>> x = 42
>>> x
42
>>> x = [x]
>>> x
[42]


x = [None, 0, 1, 42, 666, "Donald Duck", 3.14159, fractions.Fraction(355, 113)]


He wants to make a variable out of a string!
This is my interpretation of what the OP wants...

x = 'cat'  
*[insert magical code]*  
cat = []

(I think Sudhir came the closest, excepting Nosklos clever approach)
Here's a tad elaboration of Sudhirs.

class NewVariables:
    pass
x = "new_variable_name"
setattr(NewVariables, x, [ ])

Tadah!

>>>NewVariables.new_variable_name
[ ]


I can't tell if you want to take

x = 'temp'

and turn x into a list with 'temp' as its first element. That is what I inferred from your question.

If you wanted to do that, then this code will turn x into a list containing 'temp':

>>> x = 'temp'
>>> x = [] + [x]
>>> x
['temp']


This is how I interpreted your question:

def make_list(method):
    return [method.__name__]

def x():
    pass

make_list(x)
# ["x"]

Of course you can also accept a variable number of methods and return the names of each of them in a list:

def make_list_of_names(*methods):
    return [m.__name__ for m in methods]

make_list(x, str, any_function)
# ["x", "str", "any_function"]


x = 'temp'
setattr(self,x,[])
getattr(self,x)
# gives []
0

精彩评论

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

关注公众号