简体   繁体   English

如何从包含其名称的字符串中选择一个变量?

[英]How to select a variable from a string containing its name?

So I am trying to get a loop function to automatically identify the next list to append a number.所以我试图获得一个循环函数来自动识别下一个列表以附加一个数字。 The following sample code summarizes what I am trying to achieve.以下示例代码总结了我想要实现的目标。

start = 'patch'
end = 'List'

patch1List = []; patch2List = []; patch3List = []; patch4List = []; patch5List = []; patch6List = []
patch7List = []; patch8List = []; patch9List = []; patch10List = []

for patch in range(10):
    num = patch+1
    DataPoint = random.randint(1,10)

    currentPList = ('%s%d%s' % (start,num,end))
    currentPList.append(DataPoint)

I need the loop to append a data point into each of the 10 empty lists.我需要循环将数据点附加到 10 个空列表中的每一个中。

I tried to do this by setting up currentPList to identify the list to work with.我试图通过设置currentPList来识别要使用的列表来做到这一点。 The problem is, I am not quite sure how to convert currentPList , which is currently a string, into a proper object (ie. one of the empty patchList s).问题是,我不太确定如何将当前是字符串的currentPList转换为适当的对象(即空patchList )。 How do I go about doing this?我该怎么做?

You are definitely overcomplicating this.你肯定是把这个复杂化了。 Just use a list of lists:只需使用列表列表:

>>> import random
>>> num_arrays = 10
>>> array = [ [random.randint(1,10)] for i in range(num_arrays) ]
>>> array
[[2], [1], [10], [6], [9], [2], [2], [5], [8], [4]]

This way you can get the same functionality of each individual list and have it be extensible and not try to reference a variable by a concatenated string for its name.通过这种方式,您可以获得每个单独列表的相同功能,并使其具有可扩展性,而不是尝试通过连接字符串的名称来引用变量。

@Charles Drotar's answer is what you want to do, but since the title says how to convert a string to variable name, here is how you can actually create variables specified as strings (but don't do this in your circumstance): @Charles Drotar 的答案是您想要做的,但由于标题说明了如何将字符串转换为变量名,因此您可以通过以下方式实际创建指定为字符串的变量(但在您的情况下不要这样做):

s = 'string'
for i in range(1,6):
    vars().update({s + str(i): i})

>>> string2
2
>>> string5
5

What you are doing here is adding the variable entry to the namespace.您在这里所做的是将变量条目添加到命名空间。 In the absence of an object argument vars() acts like locals()在没有对象参数的情况下vars()行为类似于locals()

I think the Pythonic way to do it would be to store all the patch lists a single dictionary.我认为Pythonic 的方法是将所有补丁列表存储在一个字典中。 That way you can easily select which one by creating a unique dictionary key for each of them.这样你就可以通过为每个人创建一个唯一的字典键来轻松选择哪个。 Note also that the keys generated don't even need to be valid Python identifiers using this approach—and it would be very easy to change how many there were, since it's all done dynamically.还要注意,使用这种方法生成的密钥甚至不需要是有效的 Python 标识符——而且很容易改变有多少,因为这一切都是动态完成的。

Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions ):这就是我的意思(请注意,我还按照PEP 8 命名约定使用了变量名称):

from collections import defaultdict
import random

START, END = 'patch', 'List'
patches = defaultdict(list)  # A dictionary whose values default to lists.

for patch_num in range(1, 11):
    data_point = random.randint(1, 10)
    current_patch_list = ('%s%d%s' % (START, patch_num, END))  # Create key.
    patches[current_patch_list].append(data_point)

print(dict(patches))

Sample utput:示例输出:

{'patch1List': [5], 'patch2List': [8], 'patch3List': [4], 'patch4List': [9], 'patch5List': [10], 'patch6List': [9], 'patch7List': [5], 'patch8List': [9], 'patch9List': [8], 'patch10List': [7]}

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

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