Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 删除列表中多次出现的元素并只保留一个元素_Python 2.7 - Fatal编程技术网

Python 2.7 删除列表中多次出现的元素并只保留一个元素

Python 2.7 删除列表中多次出现的元素并只保留一个元素,python-2.7,Python 2.7,我有一个小问题。 如何检查列表中是否有相同的元素,如果列表中有相同的元素,如何在列表中只保留其中一个元素 例如,我编写了以下代码: def courses_per_student(tuple_lst): courses={} new_tuple_lst=[] for i in range(len(tuple_lst)): new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_ls

我有一个小问题。 如何检查列表中是否有相同的元素,如果列表中有相同的元素,如何在列表中只保留其中一个元素

例如,我编写了以下代码:

def courses_per_student(tuple_lst):
    courses={}
    new_tuple_lst=[]
    for i in range(len(tuple_lst)):
            new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
    for m in new_tuple_lst:      
       if not courses.has_key(m[0]):
            courses[m[0]]=[m[1]]
       else:
           courses[m[0]]=courses[m[0]]+[m[1]]
    return courses
每个学生的课程[Rina,数学,Yossi,化学,Riki,python,Rina,数学,Yossi,生物] 返回: {'rina':['math','math'],'yossi':['chemistry','biology'],'riki':['python']}

我希望“数学”在列表中只出现一次。 谢谢你

        for m in new_tuple_lst:      
           if not courses.has_key(m[0]):
                courses[m[0]]=[m[1]]
           elif m[1] not in courses[m[0]]:
               courses[m[0]]=courses[m[0]]+[m[1]]

如果顺序不重要,使用集合而不是列表也应该这样做。

您可以将列表转换为集合:
def uniqode(list):
    demolist = []
    for el in list:
        if el in demolist:
            continue
        demolist.append(el)
    return demolist