如何使用字符串格式来指定唯一变量?

2024-10-03 02:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子,我把单子变成了字符串。现在我想通过使用字符串格式将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

我得到以下错误:语法错误:无效语法

如何修复此问题并以以下格式分配新变量:

a0=33.325556 a1=59.8149016457等


Tags: 字符串in列表forlen格式num单子
1条回答
网友
1楼 · 发布于 2024-10-03 02:44:24

您当前的代码有几个问题:

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)

这是:

  1. 同时尝试print和赋值a =(因此SyntaxError
  2. 混合两种不同类型的字符串格式('%d''{0}');以及
  3. 永远不要增加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)]

相关问题 更多 >