简体   繁体   中英

How can I use string formatting to assign unique variable?

I've got a list and i've managed to turn the list into strings. Now I want to assign a variable to each item in the list by using string formatting to append a 1 onto the end of the variable.

listOne = ['33.325556', '59.8149016457', '51.1289412359']

itemsInListOne = int(len(listOne))

num = 4
varIncrement = 0

while itemsInListOne < num:
    for i in listOne:
        print a = ('%dfinalCoords{0}') % (varIncrement+1)
        print (str(listOne).strip('[]'))
    break

I get the following error: SyntaxError: invalid syntax

How can I fix this and assign a new variable in the format:

a0 = 33.325556 a1 = 59.8149016457 etc.

Your current code has a few issues:

listOne = ['33.325556', '59.8149016457', '51.1289412359']

itemsInListOne = int(len(listOne)) # len will always be an int

num = 4 # magic number - why 4?
varIncrement = 0

while itemsInListOne < num: # why test, given the break?
    for i in listOne:
        print a = ('%dfinalCoords{0}') % (varIncrement+1) # see below
        print (str(listOne).strip('[]')) # prints list once for each item in list
    break # why break on first iteration

One line in particular is giving you trouble:

print a = ('%dfinalCoords{0}') % (varIncrement+1)

This:

  1. simultaneously tries to print and assign a = (hence the SyntaxError );
  2. mixes two different types of string formatting ( '%d' and '{0}' ); and
  3. never actually increments varIncrement , so you will always get '1finalCoords{0}' anyway.

I would suggest the following:

listOne = ['33.325556', '59.8149016457', '51.1289412359']

a = list(map(float, listOne)) # convert to actual floats

You can easily access or edit individual values by index, eg

# edit one value
a[0] = 33.34

# print all values
for coord in a:
    print(coord)

# double every value
for index, coord in enumerate(a):
    a[index] = coord * 2

Looking at your previous question , it seems that you probably want pairs of coordinates from two lists, which can also be done with a simple list of 2-tuples:

listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']

coord_pairs = zip(map(float, listOne), map(float, listTwo))

Which gives:

coord_pairs == [(33.325556, 2.5929778), 
                (59.8149016457, 1.57945488999), 
                (51.1289412359, 8.57262235411)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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