Python向列表中添加信息

Python向列表中添加信息,python,list,python-2.7,Python,List,Python 2.7,我必须定义一个函数:add_infonew_info,new_list获取一个包含四个元素的元组,其中包含一个人的信息,以及一个新列表。如果该人员的姓名不在列表中,则使用新人员的信息更新该列表,并返回True以表示操作成功。否则,将打印错误,列表将保持不变,并返回False 例如: >>>d = load_file(’people.csv’) >>>d [(John’, ’Ministry of Silly Walks’, ’5555’, ’27 Octobe

我必须定义一个函数:add_infonew_info,new_list获取一个包含四个元素的元组,其中包含一个人的信息,以及一个新列表。如果该人员的姓名不在列表中,则使用新人员的信息更新该列表,并返回True以表示操作成功。否则,将打印错误,列表将保持不变,并返回False

例如:

>>>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
每当我输入一个已经在列表中的名称时,它只是将该名称添加到列表中。不知道该怎么办。有什么想法吗


提前谢谢

听起来我可能在帮你做作业,但不管怎样

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

if语句正在将字符串项[0]与列表名进行比较。因此,该测试总是失败,并转到else语句,该语句返回True。

用Python 3编程-Python语言的完整介绍是一本非常好的书。您从一开始就开始编写有用的程序。是否有特殊的原因将其保留为元组列表,而不是元组字典和键列表(可能将这两个项包装在一个类中)?对于第6行,我更希望anyitem[0]==新列表中项的名称,但是对于初学者来说,可能不太容易理解谢谢你的帮助,我使用了这段代码的一个变体,不管名字是否在列表中,我都会得到正确的结果。你如何比较字符串中的内容和列表中的内容?你如何比较字符串中的内容和列表中的内容?