我有一个列表,我已经设法将列表变成字符串。现在我想通过使用字符串格式化将一个变量分配给列表中的每个项目,以便将1附加到变量的末尾。
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
我收到以下错误:SyntaxError:语法无效
如何解决此问题并以以下格式分配新变量:
a0 = 33.325556 a1 = 59.8149016457等。
答案 0 :(得分:1)
您当前的代码存在一些问题:
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
特别是一行给你带来麻烦:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
这:
print
并指定a =
(因此SyntaxError
); '%d'
和'{0}'
);和varIncrement
,所以无论如何你总是得到'1finalCoords{0}'
。我建议如下:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
a = list(map(float, listOne)) # convert to actual floats
您可以通过索引轻松访问或编辑单个值,例如
# 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
看看你的previous question,似乎你可能想要两个列表中的坐标对,这也可以用一个简单的2元组列表来完成:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']
coord_pairs = zip(map(float, listOne), map(float, listTwo))
给出了:
coord_pairs == [(33.325556, 2.5929778),
(59.8149016457, 1.57945488999),
(51.1289412359, 8.57262235411)]