Python 将列表转换为set
时间:2020-02-23 14:42:56 来源:igfitidea点击:
在本教程中,我们将看到如何将列表转换为set
我们可以使用Python set()函数将列表转换为set.它是将列表转换为set的最简单方法。
由于set不允许重复,当我们将列表转换为set时,所有重复项将在集合中删除。
让我们通过示例来理解。
listOfStudents=['Mohan','John','Ramesh','Mohan','John']
print("List of Students:",listOfStudents)
uniqueNames=set(listOfStudents)
print("Set of uniqueNames:",uniqueNames)
listOfMarks=[8,7,6,7,8,8,7,6,7,8,9]
print("List of Makrs:",listOfMarks)
setOfMarks=set(listOfMarks)
print("Set of marks:",setOfMarks)
输出:
List of Students: ['Mohan', 'John', 'Ramesh', 'Mohan', 'John']
Set of uniqueNames: {'John', 'Ramesh', 'Mohan'}
List of Makrs: [8, 7, 6, 7, 8, 8, 7, 6, 7, 8, 9]
Set of marks: {8, 9, 6, 7}

