简体   繁体   English

如何从执行的字符串中检索值?

[英]How to retrieve a value from an executed string?

I didn't quite know how to word my question as this isn't something one would often do. 我不太清楚该如何表达我的问题,因为这不是人们经常会做的事情。 Here's my situation: 这是我的情况:

I have a list of values. 我有一个值列表。

Values= ["1","2","3","4"]

I then want to be able to separately access each of the values and combine them into a string with commas in between them. 然后,我希望能够分别访问每个值,并将它们组合成一个字符串,并在它们之间使用逗号。 I wrote a bit of code that I want to format a string ('{}'.format())in such a way so that the outcome looks like this: '1,2,3,4'. 我写了一些代码,希望以这种方式格式化字符串('{}'。format()),以使结果看起来像这样:'1,2,3,4'。 My code that I have so far (it is also the code structure that I'd prefer to use if possible) is the following: 到目前为止,我的代码如下(如果可能,它也是我更喜欢使用的代码结构):

string = "{}".format(exec(
    "Out= ''\n"
    "for value in Values:\n"
    "    Out+= value + ','\n"
    "Out"))
print(string)

If, within the string that is given as the parameter to the 'exec' function, I write "print(Out)" IE: 如果在作为“ exec”函数的参数给出的字符串中,我编写“ print(Out)” IE:

string = "{}".format(exec(
    "Out= ''\n"
    "for value in Values:\n"
    "    Out+= value + ','\n"
    "print(Out)"))

Then the program will properly run and print out "1,2,3,4", but it will not store it in 'string' (Which is to be expected) 然后,程序将正确运行并打印出“ 1、2、3、4”,但不会将其存储在“字符串”中(这是可以预期的)

I therefore thought of adding a function in order to make sure that it can return something. 因此,我考虑添加一个函数以确保它可以返回某些内容。 I wrote the following, but as expected it also didn't work. 我写了以下内容,但正如预期的那样,它也不起作用。 string is still None: 字符串仍然是None:

string = "{}".format(exec(
    "def do_stuff():\n"
    "    Out = ''\n"
    "    for value in Values :\n"
    "       Out += value + ','\n"
    "    return Out \n"
    "do_stuff()"))

Now, I do realise that this method of combining strings is nowhere near the preferred way to combine strings, but let me give you some context. 现在,我的确意识到这种组合字符串的方法远不及组合字符串的首选方法,但是让我给您一些背景知识。

I am making a game in python. 我正在用python做游戏。 There is a Character class and it contains various attributes of various data types (such as dict, list, int, str, float.... as well as some custom ones: AI, Item, ActiveSkill, PassiveSkill, Effect, Weapon, Armour etc...) Now, my plan is to be able to store the game progress in a json tree. 有一个Character类,它包含各种数据类型的各种属性(例如dict,list,int,str,float ....以及一些自定义的属性:AI,Item,ActiveSkill,PassiveSkill,Effect,武器,护甲等等...)现在,我的计划是能够将游戏进度存储在json树中。 For that I started giving each of these entities a method which will convert all of its attributes into json trees stored as strings. 为此,我开始为每个实体提供一个方法,该方法会将其所有属性转换为存储为字符串的json树。 That way, when I want to save the game and it comes to the Character, it will sort all of its attributes, but it'll also have to make a call to objects that it's referencing (such as ActiveSkills). 这样,当我要保存游戏并涉及角色时,它将对所有属性进行排序,但是还必须调用其引用的对象(例如ActiveSkills)。 For each of ActiveSkills in a list, it'll have to call for their own json syntaxed strings and combine these using commas. 对于列表中的每个ActiveSkills,都必须调用自己的json语法字符串,并使用逗号将它们组合在一起。

Here's some of my code to help you understand what I want to do: 这是我的一些代码,可帮助您了解我想做什么:

json += \
    '"ActiveSkills":[{oActiveSkills}],' \
    '"PassiveSkills":[{oPassiveSkills}].' \
    '"Effects":[{oEffects}],'.format(
        oActiveSkills=exec(
            "Skills = ''\n"
            "for skill in self.ActiveSkills:\n"    # ActiveSkills is a list of ActiveSkill objects
            "    Skills+=skill.encode_to_json() + ','\n"
            "return Skills"),
        oPassiveSkills=exec(
            "Skills = ''\n"
            "for skill in self.PassiveSkills:\n"    # PassiveSkills is a list of PassiveSkill objects
            "    Skills+=skill.encode_to_json() + ','\n"
            "return Skills"),
        oEffects=exec(
            "Effects = ''\n"
            "for effect in self.Effects:\n"    # Effects is a list of Effect objects
            "    Effects+=effect.encode_to_json() + ','\n"
            "return Effects"))

I know that this code currently doesn't run, as you can only return from within a function, but I really don't know how to go about it in a quick and easy way. 我知道该代码目前无法运行,因为您只能从一个函数中返回,但是我真的不知道如何快速简便地进行操作。

One solution that I have saved up as a last resort is to just do everything by hand. 我没有想到的一种解决方法是手动完成所有操作。 IE: Have some kind of for loop that creates a string from returned values. IE:具有某种for循环,可根据返回的值创建一个字符串。 Add this string to the json string, after which you will manually open and close with "},{" and make sure that there isn't a "," at the end. 将此字符串添加到json字符串中,之后您将使用“},{”手动打开和关闭,并确保最后没有“,”。 Then repeat this for PassiveSkills and Effects also. 然后对PassiveSkills and Effects也重复此步骤。 Finally, close the json string with "}," and add it to the 'json' (string type) variable... 最后,使用“}”关闭json字符串,并将其添加到“ json”(字符串类型)变量中...

I want to minimise the space taken up by this, and I want this system to be flexible, so that no matter how many skills in a list that you have, you could continue adding more and more of these json strings without changing the code. 我想最小化它占用的空间,并且我希望该系统具有灵活性,以便无论列表中有多少技能,您都可以继续添加越来越多的这些json字符串而无需更改代码。

To join a list using ',' : 要使用','加入列表:

Values = ["1","2","3","4"]
result = ",".join( Values )
print(result)

More info about str.join(iterable) can be found here in the online documentation. 有关更多信息str.join(iterable) ,可以发现这里的在线文档。

For a better solution to store dictionaries and lists (and, using pickle, objects), you should look at the json and pickle packages in the Python Standard Library. 为了更好地存储字典和列表(以及使用pickle对象),您应该查看Python标准库中的json和pickle包。

For example, with json: 例如,使用json:

import json

mydata = {}
mydata['hello'] = { 'value1':1, 'valuuelist':[1,2,3,4] }

print(json.dumps(mydata))

Output: 输出:

{"hello": {"valuuelist": [1, 2, 3, 4], "value1": 1}}

So, don't roll your own encoder, unless you really have to. 因此,除非确实需要,否则不要滚动自己的编码器。

For joining each element of a sequence into a string you can use join method. 要将序列中的每个元素连接到字符串中,可以使用join方法。

   L=['1','2','3']
   string=",".join(L)
   print(L)

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

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