2012-12-09 82 views
0

「地址文件」在這種情況下文件處理如何工作?

100 Main Street 
23 Spring Park Road 
2012 Sunny Lane 
4 Martin Luther King Drive 

「地址列表」

[['100', 'Main', 'Street'], 
['23', 'Spring Park', 'Road'], 
['2012', 'Sunny', 'Lane'], 
['4', 'Martin Luther King', 'Drive']] 

numbers_file = open("address_file.txt", "r") 
def load_addresses(numbers_file): 
    addresses = [] # <-- Create a list for sublist 
    for line in numbers_file: 
     address = [] # <-- Create a sublist 
     parts = line.split() # <-- split into lists by whitespace 
     address.append(parts[0]) # <--- I know this will take first elements of the   lists and appended (back of the list) to sublist. 
     name = '' # <--- name to attach such as 'Spring' 'Park' into 'Spring' 
     for i in range(1, len(parts) - 1): # <--- Why is the range like this? is it because we ignore first element since its already in good form and since its index we -1? 
      name += parts[i] + ' ' # <--- ?? 
      address.append(name.strip()) # <--- I guess this is to wipe out whitespace front and back 
      address.append(parts[-1]) # <---??? 
      addresses.append(address) # <--- append the sublist into list 

    return addresses 

那些我放在旁邊???它是令人困惑的部分。有人能澄清他們嗎?

+0

是list'這裏你想要的結果了'地址? – mgilson

+0

是的,我不知道這個過程如何工作 –

+0

對不起,我是這個網站的新手。我會盡力跟隨。 –

回答

1
def line_split(line): 
    ls = line.split() 
    return [ls[0],' '.join(ls[1:-1]), ls[-1]] 

with open(datafile) as fin: 
    address_list = [ line_split(line) for line in fin ] 
    #address_list = map(line_split,fin) # would also work too. 

解釋的問題標線:

for i in range(1, len(parts) - 1): 

這遍歷該列表中的指標,但它跳過第一和最後一個索引。更慣用的方式做這將是:

for part in parts[1:-1]: 

,然後你將與part取代parts[i]在循環以後。

name += parts[i] + ' ' # <--- ?? 

這需要name,並增加了parts[i]它和' '。換句話說,它是一回事以下任何一項:

name = name + parts[i] + ' ' 
name = "%s%s "%(name,parts[i]) 
name = "{0}{1} ".format(name,parts[i]) 

而行:

address.append(parts[-1]) # <---??? 

追加備件清單發送到address列表的最後一部分。

+0

是的,謝謝你的回答,但我希望解釋我的功能不是......另一個功能。 –

0

或許這將幫助:

>>> line = '100 Main Street' 
>>> parts = line.split() 
>>> name = '' 
>>> len(parts)-1 
2 
>>> for i in range(1,2): 
... print parts[i] + ' ' 
... print parts[-1] 
... 
Main # <-- there is an extra space here after 'Main' 
Street 
相關問題