2014-02-27 28 views
0

我有一個列表,我設法將列表變成字符串。現在我想通過使用字符串格式將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等

+2

這不是一個好主意。相反,使'a'字典或列表,並把你的價值觀結構。 – BrenBarn

+0

我知道這不是理想的,但我需要爲每個字符串儘快分配一個唯一的變量 – BubbleMonster

+2

我懷疑它。你能解釋爲什麼你認爲你需要以'a0','a1'等等的方式來訪問這些值,而不是'a [0]','a [1]'等等。 – BrenBarn

回答

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) 

此:

  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 

您可以輕鬆地訪問或指數,例如編輯單個值你previous question

# 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 

來看,似乎你可能想對座標從兩個列表,這也可以用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)] 
相關問題