向Python lis添加信息

2024-07-02 10:11:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须定义一个函数: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’)]

到目前为止,我的代码如下:

^{pr2}$

每当我输入一个已经在列表中的名称时,它只会将该名称添加到列表中。不知道该怎么办。有什么想法吗?在

提前谢谢!在


Tags: ofinfoadd列表shopjohnmaymarch
2条回答

if语句正在将字符串(项[0])与列表(名称)进行比较。所以这个测试总是失败,它会移到else语句,返回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

相关问题 更多 >