Python将信息添加到列表中

时间:2013-03-23 00:16:14

标签: python list python-2.7

我必须定义一个函数:add_info(new_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

每当我输入已经在列表中的名称时,它只会将名称添加到列表中。无法解决该怎么做。有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分: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 :(得分:0)

您的if语句将字符串(item [0])与列表(name)进行比较。因此测试总是失败并且它会移动到返回True的else语句。