我是python的新手,所以對於簡單的問題表示歉意。我當然錯過了讓我困惑的東西。Python:分割字符串多次;嵌套數據結構
這與嵌套,分裂有關,我猜循環,但它不適合我。
因此,這裏是我的原始字符串:
name_scr = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'
我試圖創建一個數據結構 - 字典與內它的名字和分數。
原來這就是我開始:
test_scr = { }
new_name_scr = [list.split('-') for list in name_scr.split('|')]
# [['alvinone', '90,80,70,50'], ['simonthree', '99,80,70,90'], ['theotwo', '90,90,90,65']]
# this is not right, and since the output is a list of lists, I cannot split it again
我得到這個在逗號第三次卡住分裂。於是我嘗試以下方法:
test_scores = {}
for student_string in name_scr.split('|'):
for student in student_string.split('-'):
for scores in student.split(','):
test_scores[student] = [scores]
#but my result for test_scores (below) is wrong
#{'alvinone': ['alvinone'], '99,80,70,90': ['90'], 'theotwo': ['theotwo'], '90,80,70,50': ['50'], '90,90,90,65': ['65'], 'simonthree': ['simonthree']}
我希望它看起來像這樣:
{'alvinone': [99 80 70 50], 'simonthree': [90 80 70 90], 'theotwo': [90 90 90 65]}
所以,當我這樣做:
print test_scores['simonthree'][2] #it's 70
請幫我在這裏。請記住,我是python全新的,所以我現在還不太瞭解。謝謝。
你不應該命名您的變量列表,列表'()'是BIF(見http://docs.python.org/library/functions.html#列表) – LarsVegas 2012-08-13 13:56:27