2013-03-23 145 views
1

我必須定義一個函數:add_info(new_info,new_list)帶有一個包含關於一個人的信息和一個新列表的四個元素的元組。如果此人的姓名尚未在列表中,則列表中將更新新人的信息,並返回True以表示操作已成功。否則,將打印一個錯誤,列表不變,並返回False。Python將信息添加到列表中

例如:

>>>d = load_file(’people.csv’) 
>>>d 
[(John’, ’Ministry of Silly Walks’, ’5555’, ’27 October’), 
(’Eric’, ’Spamalot’, ’5555’, ’29 March’)] 
>>>add_info((’John’, ’Cheese Shop’, ’555’, ’5 May’), d) 
John is already on the list 
False 
>>>d 
[(John’, ’Ministry of Silly Walks’, ’5555’, ’27 October’), 
(’Eric’, ’Spamalot’, ’5555’, ’29 March’)] 
>>>add_info((’Michael’, ’Cheese Shop’, ’555’, ’5 May’), d) 
True 
>>>d 
[(John’, ’Ministry of Silly Walks’, ’5555’, ’27 October’), 
(’Eric’, ’Spamalot’, ’5555’, ’29 March’), 
(’Michael’, ’Cheese Shop’, ’555’, ’5 May’)] 

到目前爲止我的代碼看起來是這樣的:

def load_file(filename): 
with open(filename, 'Ur') as f: 
    return list(f) 

def save_file(filename, new_list): 
with open(filename, 'w') as f: 
    f.write('\n'.join(new_list) + '\n') 

def save_file(filename, new_list): 
with open(filename, 'w') as f: 
    f.write(line + '\n' for line in new_list) 


def save_file(filename, new_list): 
with open(filename, 'w') as f: 
    for line in new_list: 
     f.write(line + '\n') 

def add_info(new_info, new_list): 


name = new_info 

for item in new_list: 
    if item == name: 
     print str(new_info) , "is already on the list." 
     return False 
else: 
    new_list.append(new_info) 
    return True 

每當我把已在列表中的名字,它只是增加了名稱列表。無法解決做什麼。有任何想法嗎?

在此先感謝!

+0

「Python 3中的編程 - Python語言的完整介紹」是一本很好的書。您從一開始就開始編寫有用的程序。 – 2013-03-23 00:29:41

+0

是否有一些特別的理由讓它保持爲元組列表,而不是像元組字典和鍵列表(可能將這兩個元素包裝在一個類中)? – 2013-03-23 00:44:07

回答

0

聽起來像我可能做你的功課你,但無論如何...

def add_info(new_info, new_list): 
    # Persons name is the first item of the list 
    name = new_info[0] 

    # Check if we already have an item with that name 
    for item in new_list: 
     if item[0] == name: 
      print "%s is already in the list" % name 
      return False 

    # Insert the item into the list 
    new_list.append(new_info) 
    return True 
+1

對於第6行,我更喜歡'如果有((item [0] ==名稱爲new_list中的項目))',但可能對初學者不可讀 – minism 2013-03-23 00:33:26

+0

感謝您的幫助,我使用了此代碼的變體,無論名稱是否在列表中,都要保持True。 – 2013-03-23 02:21:59

0

你的if語句是一個字符串(項[0])比較列表(名稱)。所以那個測試總是失敗,並且它移動到返回True的else語句。

+0

如何比較字符串中的內容與列表中的內容? – 2013-03-23 03:33:42

+0

如何將字符串中的內容與列表中的內容進行比較? – 2013-03-23 04:00:01