2016-08-21 210 views
2

我有一個drawingnumbers的列表,我試圖拆分這些字符串,然後附加到一些列表。遍歷列表 - 拆分字符串

我希望結束了一些列表,其中包含每個相關的原始字符串片。

當時我的定義是遍歷列表,但覆蓋變量,而不是追加它們。因此,我爲每個變量都有一個條目,這些條目對應於列表的最終條目。

任何人都可以請幫忙嗎?

# drawingnumber split 

drawingnumber = ["AAA601-XXX-A-L00-1028-DR-GA-200-001", 
"AAA601-XXX-A-L10-1028-DR-GA-200-001", 
"AAA601-XXX-A-L00-1029-DR-GA-200-001", 
"AAA601-XXX-A-L00-1029-DR-GA-200-XXX"] 

building = [] 
buildinglist = [] 
originator = [] 
discipline = [] 
level = [] 
scope = [] 
drawingtype = [] 
drawingsubtype = [] 
numbera = [] 
numberb = [] 

for i in drawingnumber: 
    building, originator, discipline, level, scope, \ 
    drawingtype,drawingsubtype, numbera, numberb = i.split("-") 

print("building:", building) 
print("originator: ", originator) 
print("discipline: ", discipline) 
print("level: ", level) 
print("scope: ", scope) 
print("drawingtype: ", drawingtype) 
print("drawingsubtype", drawingsubtype) 
print("drawingident", numbera, "-", numberb) 

回答

2

您可以使用zip列表中分裂的每個元素後轉你的清單爲:

zip(*[i.split("-") for i in drawingnumber]) 

,並將它們分配到列表中的名稱:

building, originator, discipline, level, scope, \ 
drawingtype, drawingsubtype, numbera, numberb = zip(*[i.split("-") for i in drawingnumber]) 

輸出示例:

building 
# ('AAA601', 'AAA601', 'AAA601', 'AAA601') 

originator 
# ('XXX', 'XXX', 'XXX', 'XXX') 

numberb 
# ('001', '001', '001', 'XXX') 
+2

打我吧,upvoted – Mureinik

+0

完美 - 謝謝大家。 – Jup

+0

@Jup:如果答案有幫助,考慮upvoting /接受它(左邊的綠色勾號)。 – Jan

0

只要改變

for i in drawingnumber: 
    building, originator, discipline, level, scope, drawingtype,drawingsubtype, numbera, numberb = i.split("-") 

到:

for i in drawingnumber: 
    building_, originator_, discipline_, level_, scope_, drawingtype_,drawingsubtype_, numbera_, numberb_ = i.split("-") 
    building.append(building_) 
    originator.append(originator_) 
    ...etc... 

分裂valeus重新定義你的變量,你要在這裏做什麼,每次基本上是附上那些你創建的列表,還搭載複數名像列表:建築並附加單數變量給他們

0
drawingnumber = ["AAA601-XX1-A-L00-1028-DR-GA-200-001", 
"AAA602-XX2-A-L10-1028-DR-GA-200-001", 
"AAA603-XX3-A-L00-1029-DR-GA-200-001", 
"AAA604-XX4-A-L00-1029-DR-GA-200-XXX"] 

building = [] 
buildinglist = [] 
originator = [] 
discipline = [] 
level = [] 
scope = [] 
drawingtype = [] 
drawingsubtype = [] 
numbera = [] 
numberb = [] 

for i in drawingnumber: 
    j = i.split('-') 
    building.append(j[0]) 
    buildinglist.append(j[1]) 


for i in range(len(drawingnumber)): 
    print("building:", building[i]) 
    print("buildinglist:", buildinglist[i])