Python: Create a variable using something other than a plain string? [duplicate]

混江龙づ霸主 提交于 2020-04-17 20:38:12

问题


In a different question I tried to use an enumerate and for element to create a pandas dataframe using the element as the name. It turns out the problem is more general. Is there anyway to set a variable value using something other than a plain string? In Bash this is done with the Read command, which takes the previous output into a subshell and assigns it to a variable name (I'll post my question on that below).

Any way to do this in Python? i.e., something simple like:

list1[0] = pd.dataframe(data), where list1[0] is a string. Or similarly using a dict key where the value is a dataframe:

for i in dict1: i = dict1[key] or for i in dict1: function(i) = dict1[key]?

The latter doesn't work using str() or any function because the error complains "SyntaxError: can't assign to function call", but maybe something similar?

Python: How can I use an enumerate element as a string?

https://unix.stackexchange.com/questions/338000/bash-assign-output-of-pipe-to-a-variable

https://unix.stackexchange.com/questions/574920/bash-how-to-get-stdout-to-console-and-also-pipe-to-next-command

EDIT: Okay, well, after extended discussion with @juanpa.arrivillaga, he explained that strings are not plain strings as in Bash. Let's see if I have this right.. they are string objects stored in dict objects. (even integers are stored as objects unless using numpy or pandas which expand on Python arrays). Inside a for i in dict1: loop print(i) works because 'print will call str implicitly on any object you pass to it'. i = value does not because 'think of variables as nametags you throw on objects' and i is being resolved in its for loop scope as a dict object key. I'm not sure why, but variable 'nametags' cannot be string objects.

A workaround using globals() kind of mentioned in the Duplicate answers exists:

for key in dict1: globals()[key] = pd.DataFrame()

This is because in CPython, they used actual python objects to implement the global namespaces. It might be possible to 'maybe use ctypes to modify the namespace array in a local scope', as another workaround is to use SimpleNamespace to create a new object to store variables (presumably because they are stored as objects, the same as in globals(). And to wrap up, 'setattr(sys.modules[_name_], var_name, var_value) is equivalent to globals()[var_name] = var_value'.


回答1:


Sorry it's quite hard to understand what exactly the question is.

for i in dict1: function(i) = dict[key]

A couple of problems with this: the thing on the left is what you're assigning, so the syntax should be dict[key] = function(i) (but don't call your dicts 'dict' because that's a reserved keyword). This is assuming key is defined somewhere. This is why you're getting the error you describe - you cant assign to a function call, you assign to variables.

As for storing things in list, you can put whatever you like in there, same with dictionaries. For example:

import pandas as pd

ls = [pd.DataFrame(), 'Hello']

d = {
    'a': pd.DataFrame(),
    1: pd.DataFrame()
}

print(ls)
print(d['a'])
print(d[1])



回答2:


I think this issue can be solved with dictionaries:


var_names = ['your_string', 'your_second_string']

dict = {}
for i, var_name in enumerate(var_names):
    var_name = f'var_name{i}'
    dict[var_name] = pd.DateFrame([])


来源:https://stackoverflow.com/questions/61002404/python-create-a-variable-using-something-other-than-a-plain-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!