How to create a List given a variable “x” in Pytho

2020-05-10 15:46发布

Python:

I have a variable say x. I need to create a list of name "x"

标签: python
7条回答
狗以群分
2楼-- · 2020-05-10 16:19
x = [None, 0, 1, 42, 666, "Donald Duck", 3.14159, fractions.Fraction(355, 113)]
查看更多
3楼-- · 2020-05-10 16:22

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"]
查看更多
啃猪蹄的小仙女
4楼-- · 2020-05-10 16:26

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.

查看更多
甜甜的少女心
5楼-- · 2020-05-10 16:26

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']
查看更多
家丑人穷心不美
6楼-- · 2020-05-10 16:30

Then just do it:

>>> x = 42
>>> x
42
>>> x = [x]
>>> x
[42]
查看更多
闹够了就滚
7楼-- · 2020-05-10 16:32
x = 'temp'
setattr(self,x,[])
getattr(self,x)
# gives []
查看更多
登录 后发表回答