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.
I tried to do this by setting up currentPList to identify the list to work with. 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 patchLists). How do I go about doing this?
python string python-2.7
add a comment |
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.
I tried to do this by setting up currentPList to identify the list to work with. 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 patchLists). How do I go about doing this?
python string python-2.7
1
the title is misleading. strings are objects. and the term you're looking for isvariable names
– Paritosh Singh
Jan 1 at 8:52
2
patch1List,patch2List,patch3List, ... It looks like you want to use a list instead of 10 single variables.
– Klaus D.
Jan 1 at 8:56
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
1
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07
add a comment |
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.
I tried to do this by setting up currentPList to identify the list to work with. 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 patchLists). How do I go about doing this?
python string python-2.7
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.
I tried to do this by setting up currentPList to identify the list to work with. 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 patchLists). How do I go about doing this?
python string python-2.7
python string python-2.7
edited Jan 1 at 9:48
martineau
67.8k1090183
67.8k1090183
asked Jan 1 at 8:48
Ang Jit Wei AaronAng Jit Wei Aaron
67111
67111
1
the title is misleading. strings are objects. and the term you're looking for isvariable names
– Paritosh Singh
Jan 1 at 8:52
2
patch1List,patch2List,patch3List, ... It looks like you want to use a list instead of 10 single variables.
– Klaus D.
Jan 1 at 8:56
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
1
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07
add a comment |
1
the title is misleading. strings are objects. and the term you're looking for isvariable names
– Paritosh Singh
Jan 1 at 8:52
2
patch1List,patch2List,patch3List, ... It looks like you want to use a list instead of 10 single variables.
– Klaus D.
Jan 1 at 8:56
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
1
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07
1
1
the title is misleading. strings are objects. and the term you're looking for is
variable names– Paritosh Singh
Jan 1 at 8:52
the title is misleading. strings are objects. and the term you're looking for is
variable names– Paritosh Singh
Jan 1 at 8:52
2
2
patch1List, patch2List, patch3List, ... It looks like you want to use a list instead of 10 single variables.– Klaus D.
Jan 1 at 8:56
patch1List, patch2List, patch3List, ... It looks like you want to use a list instead of 10 single variables.– Klaus D.
Jan 1 at 8:56
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
1
1
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07
add a comment |
3 Answers
3
active
oldest
votes
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.
1
why not justarray = [ [random.randint(1,10)] for i in range(num_arrays)]for a one-liner?
– Jean-François Fabre
Jan 1 at 9:24
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
add a comment |
@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):
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()
1
It's worth noting that the python docs explicitly state thatlocalsshould not be modified.
– snakecharmerb
Jan 1 at 9:31
add a comment |
I think the Pythonic way to do it would be to store all the patch lists a single dictionary. 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.
Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions):
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]}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994142%2fhow-to-select-a-variable-from-a-string-containing-its-name%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
1
why not justarray = [ [random.randint(1,10)] for i in range(num_arrays)]for a one-liner?
– Jean-François Fabre
Jan 1 at 9:24
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
add a comment |
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.
1
why not justarray = [ [random.randint(1,10)] for i in range(num_arrays)]for a one-liner?
– Jean-François Fabre
Jan 1 at 9:24
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
add a comment |
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.
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.
edited Jan 1 at 9:31
answered Jan 1 at 9:03
Charles DrotarCharles Drotar
1217
1217
1
why not justarray = [ [random.randint(1,10)] for i in range(num_arrays)]for a one-liner?
– Jean-François Fabre
Jan 1 at 9:24
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
add a comment |
1
why not justarray = [ [random.randint(1,10)] for i in range(num_arrays)]for a one-liner?
– Jean-François Fabre
Jan 1 at 9:24
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
1
1
why not just
array = [ [random.randint(1,10)] for i in range(num_arrays)] for a one-liner?– Jean-François Fabre
Jan 1 at 9:24
why not just
array = [ [random.randint(1,10)] for i in range(num_arrays)] for a one-liner?– Jean-François Fabre
Jan 1 at 9:24
1
1
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
Duh! @Jean-FrançoisFabre you are absolutely right I just overlooked that :/. I'll update the answer with your suggestion.
– Charles Drotar
Jan 1 at 9:30
add a comment |
@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):
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()
1
It's worth noting that the python docs explicitly state thatlocalsshould not be modified.
– snakecharmerb
Jan 1 at 9:31
add a comment |
@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):
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()
1
It's worth noting that the python docs explicitly state thatlocalsshould not be modified.
– snakecharmerb
Jan 1 at 9:31
add a comment |
@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):
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()
@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):
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()
answered Jan 1 at 9:16
Attack68Attack68
1,0681411
1,0681411
1
It's worth noting that the python docs explicitly state thatlocalsshould not be modified.
– snakecharmerb
Jan 1 at 9:31
add a comment |
1
It's worth noting that the python docs explicitly state thatlocalsshould not be modified.
– snakecharmerb
Jan 1 at 9:31
1
1
It's worth noting that the python docs explicitly state that
locals should not be modified.– snakecharmerb
Jan 1 at 9:31
It's worth noting that the python docs explicitly state that
locals should not be modified.– snakecharmerb
Jan 1 at 9:31
add a comment |
I think the Pythonic way to do it would be to store all the patch lists a single dictionary. 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.
Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions):
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]}
add a comment |
I think the Pythonic way to do it would be to store all the patch lists a single dictionary. 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.
Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions):
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]}
add a comment |
I think the Pythonic way to do it would be to store all the patch lists a single dictionary. 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.
Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions):
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]}
I think the Pythonic way to do it would be to store all the patch lists a single dictionary. 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.
Here's what I mean (Note I also made the variable names used following the PEP 8 Naming Conventions):
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]}
edited Jan 2 at 11:58
answered Jan 1 at 10:09
martineaumartineau
67.8k1090183
67.8k1090183
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994142%2fhow-to-select-a-variable-from-a-string-containing-its-name%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
the title is misleading. strings are objects. and the term you're looking for is
variable names– Paritosh Singh
Jan 1 at 8:52
2
patch1List,patch2List,patch3List, ... It looks like you want to use a list instead of 10 single variables.– Klaus D.
Jan 1 at 8:56
Hi Klaus, sorry if the codes looked a little deceiving. This is a simplified code of what I am trying to do on a bigger scale. Basically, in each of the patchLists, they all will have hundreds of data point, each list, consisting of different data points. Thus, I had it laid out like this.
– Ang Jit Wei Aaron
Jan 1 at 9:02
1
You still need to use a list. Just have a list with 10 sub lists
– dangee1705
Jan 1 at 9:07