Home > Software design >  Add multiple unknowns to a string in Pyton
Add multiple unknowns to a string in Pyton

Time:11-19

I need to add to the line:

url="items.point&point1={item},{item}&point2C{item},{item}"

four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop.

I tried many different options for how to do this, but the program displays a lot of extra values.

My code:

import numpy as np
coordinates=[]
for item in np.arange(45.024287,45.024295,0.000001):
    coordinates.append("%.6f" %item)
    for item in np.arange(45.024287,45.024295,0.000001):
        coordinates.append("%.6f" %item)
urls=[]
for item in (coordinates):
    urls.append(f"items.point&point1{item},{item}&point2={item},{item}")
print(urls)

I need to get this result:

"items.point&point1=45.024295,45.024295&point2=39.073557,45.005125","items.point&point1=45.024294,45.024294&point2=39.073557,45.005125"...Etc 

With different coordinates

But I am getting repeated values ​​due to the fact that the loop is in a loop. Can you tell me how you can substitute several variables in a string without doubling the values?Please

CodePudding user response:

I remember reading recently something related to your problem. Can't remember the post, else I'd link it, but I took notes about the beautiful method! So try this:

urls=[]
for item1, item2 in zip(*[iter(coordinates)]*2):
    urls.append(f"items.point&point1{item1},{item2}&point2=39.073557,45.005125")
print(urls)

CodePudding user response:

There's no need for the coordinates array. Just append to urls in the nested for loop to get all the combinations of item values.

for item1 in np.arange(45.024287,45.024295,0.000001):
    for item2 in np.arange(45.024287,45.024295,0.000001):
        urls.append(f"items.point&point1={item1},{item2}&point2=39.073557,45.005125")
  • Related