Concatenating variable names in Python [duplicate] - python

This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
How can I select a variable by (string) name?
(5 answers)
Closed 6 years ago.
I need to check variables looking like this:
if name1 != "":
(do something)
Where the number right after "name" is incremented between 1 and 10.
Do I need to write the test ten times or is there a way (without using an array or a dict) to "concatenate", so to speak, variable names?
I'm thinking about something like this:
for i in range(10):
if "name" + str(i) != "":
(do something)
Edit: I can't use a list because I'm actually trying to parse results from a Flask WTF form, where results are retrieved like this:
print(form.name1.data)
print(form.name2.data)
print(form.name3.data)
etc.

Use a list, such as:
names = ['bob', 'alice', 'john']
And then iterate on the list:
for n in names:
if n != "":
(do something)
or you could have a compounded if statement:
if (name1 != "" or name2 != "" or name3 != "")
The best solution would be to use solution #1.

If you cannot use a list or a dict, you could use eval
for i in range(10):
if eval("name" + str(i)) != "":
(do something)

First of all, your app have invalid logic. You should use list, dict or your custom obj.
You can get all variable in globals. Globals is a dict.
You can do next:
for i in range(10):
if globals().get('name%d' % i):
# do something

Related

Way to dynamically create new variables based on length of list in Python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 months ago.
Is there any way that I can automatically create new variables based on how many items I have in a Python list?
For instance, if I have a variable like this:
var = (json.loads(requests.get(list[0])).text)
Is it possible to automatically create additional variables like this, depending on the length of my list? I'd like to avoid manually writing out all my variables. Let's say my list has 4 items (length = 4).
var = (json.loads(requests.get(list[0])).text)
var1 = (json.loads(requests.get(list[1])).text)
var2 = (json.loads(requests.get(list[2])).text)
var3 = (json.loads(requests.get(list[3])).text)
I would appreciate any help. Thank you.
Why don't you try to use a dict to handle this problem?
vars = {f'var{i}': json.loads(requests.get(yourlist[i])).text for i in range(len(yourlist))}
You can access your variables: vars['var1'] or vars.get('var1')
In general, creating new variables during the program execution isn't a good ideia.
The direct answer to your question is to add the values in the global dictionary. It can be done with globals, eval, exec. I don't recommend to do that because if you have a long list which change size then you have to remember how many elements you have.
Here an abstraction of the problem:
var_str_pattern = 'var{}'
val = ['smt', 'else']
for i, v in enumerate(val, start=1):
globals()[var_str_pattern.format(i)] = v
print(var1)
#smt
print(var2)
#else
For the specific question:
n = 3
var_str_pattern = 'var'
for i in range(1, n+1):
globals()[f'{var_str_pattern}{i}'] = json.loads(requests.get(list[i])).text
print(var1)
print(var2)
print(var3)
You should use a dictionary approach as in the answer of Riqq.

convert list into string? [duplicate]

This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).

Using a string as variable [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.
for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])
I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.
Thanks in advance
You are trying to do this:
test1 = something
test2 = something else
for i in range(1,2):
print('test' + str(i))
however, that won't work because strings cannot be used as variable names. You can cheat somewhat by using locals(), which creates a dictionary of local variables:
test1 = something
test2 = something else
for i in range(1,2):
print(locals()['test' + str(i)])
but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.
d = {'test1': something,
'test2': something else}
for i in range(1,2):
print(d['test' + str(i)])
# or even better
tests = [something, something else]
for test in tests:
print(test)
# even better, what you're trying to do is this:
for i, test in enumerate(tests):
period_writer.writerow([i+1, max(test)])
This makes it much clearer that the variables belong together and will run faster to boot.

Concise Way of Get Matching Element in List [duplicate]

This question already has answers here:
Find first sequence item that matches a criterion [duplicate]
(2 answers)
Closed 7 years ago.
I have a list that looks like
[{'name': 'red', 'test':4},... {'name': 'reded', 'test':44}]`
I have a name (for example: reded) and I want to find the dictionary in the list above that has name in the dictionary set to reded. What is a concise way of doing so?
My attempts look something similar to
x = [dict_elem for dict_elem in list_above if dict_elem['name']==reded]
Then I do
final_val = x[0]
if the name gets matched. This can also be done with a for loop but it just seems like there is a simple one-liner for this. Am I missing something?
You're pretty much there. If you use a generator- rather than list-comprehension, you can then pass it to next, which takes the first item.
try:
x = next(dict_elem for dict_elem in list_above if dict_elem['name'] == reded)
except StopIteration:
print "No match found"
Or
x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
print "No match found"

How to print the variable name [duplicate]

This question already has answers here:
How to retrieve a variable's name in python at runtime?
(9 answers)
Closed 9 years ago.
I've designed a code that calculates the percentage of 'CG' appears in a string; GC_content(DNA).
Now I can use this code so that it prints the the value of the string with the highest GC-content;
print (max((GC_content(DNA1)),(GC_content(DNA2)),(GC_content(DNA3)))).
Now how would I get to print the variable name of this max GC_content?
You can get the max of some tuples:
max_content, max_name = max(
(GC_content(DNA1), "DNA1"),
(GC_content(DNA2), "DNA2"),
(GC_content(DNA3), "DNA3")
)
print(max_name)
If you have many DNA variables you could place them in a list
DNA_list = [DNA1, DNA2, DNA3]
I would coerce them into a dictionary to associate the name with the raw data and result.
DNA_dict = dict([("DNA%i" % i, {'data': DNA, 'GC': GC_Content(DNA)}) for i, DNA in enumerate(DNA_list)])
Then list comprehension to get the data you want
name = max([(DNA_dict[key]['GC'], key) for key in DNA_dict])[1]
This has the benefit of allowing variable list length
You seem to want
max([DNA1, DNA2, DNA3], key=GC_content)
It's not what you asked for but it seems to be what you need.

Categories