therMapper
therMapper

Reputation: 43

Python: How to create new variable in each iteration of a for loop?

I need to create a long text string out of 3 lists. This text string has to be in a very specific format where there's an element from each list separated by a space, and each group has a semicolon afterwards. The below script should run:

import math

reclassInt = [1, 2, 3, 4, 5, 6]
minValueRange = [512, 550.0, 600.0, 650.0, 700.0, 750.0]
maxValueRange = [550.0, 600.0, 650.0, 700.0, 750.0, 755]

for numbers in reclassInt:
    newNums = numbers-1
    longString = str(minValueRange[newNums]) + " " + str(maxValueRange[newNums]) + " " + str(reclassInt[newNums]) + ";" 
    print longString

This will return 6 lines, the first being:

512 550.0 1;

Instead of printing these strings, I want to set a variable to each of them. I want this variable to have a unique name for each iteration of the loop( based on reclassInt items).

Ideally this could create variables like line1, line2, ect to equal the string outputs from each iteration. Then I could string these together outside the loop to get my desired string.

To be clear my end goal is this exact string:

"512 550.0 1;550.0 600.0 2;600.0 650.0 3;650.0 700.0 4;700.0 750.0 5;750.0 755 6;"

Thanks All,...

Upvotes: 0

Views: 5942

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174758

How about this:

>>> d = {i+1:v for i,v in enumerate(zip(minValueRange, maxValueRange))}
>>> d
{1: (512, 550.0),
 2: (550.0, 600.0),
 3: (600.0, 650.0),
 4: (650.0, 700.0),
 5: (700.0, 750.0),
 6: (750.0, 755)}

Then to print your string:

>>> for k,v in d.iteritems():
...    print('{} {} {};'.format(v[0], v[1], k))
...
512 550.0 1;
550.0 600.0 2;
600.0 650.0 3;
650.0 700.0 4;
700.0 750.0 5;
750.0 755 6;

To get the string in one line, as per your update:

>>> ''.join('{} {} {};'.format(v[0], v[1], k) for k,v in d.iteritems())
'512 550.0 1;550.0 600.0 2;600.0 650.0 3;650.0 700.0 4;700.0 750.0 5;750.0 755 6;'

Also if that's your only requirement you don't need to generate the dictionary and can combine everything into this:

>>> ''.join('{} {} {};'.format(v[0], v[1], k+1) for k,v in enumerate(zip(minValueRange, maxValueRange)))
'512 550.0 1;550.0 600.0 2;600.0 650.0 3;650.0 700.0 4;700.0 750.0 5;750.0 755 6;'

Upvotes: 2

aIKid
aIKid

Reputation: 28352

To make things much simpler, and better, you can use a dictionary:

longStrings= {}
for numbers in reclassInt:
    newNums = numbers-1
    d["longString_%d"%numbers] = str(minValueRange[newNums]) + " " + str(maxValueRange[newNums]) + " " + str(reclassInt[newNums]) + ";" 
    bs = "ls" + str(numbers)

Upvotes: 2

Related Questions