1.使用set函數
>>> list1 = [7,8,7,8,9,10]
>>> set(list1)
{8, 9, 10, 7}
2.使用字典函數
>>> list1 = [7,8,7,8,9,10]
>>> b = dict.fromkeys(list1)
>>> b
{7: None, 8: None, 9: None, 10: None}
>>> c = list(b.keys())
>>> c
[7, 8, 9, 10]
fromkeys()的用法
用於創建並返回一個新的字典。兩個參數:第一個是字典的鍵,第二個(可選)是傳入鍵的值,默認為None。 第一個值可以是字符串、列表、元祖、字典
-
實例一:
#列表 >>> dict1 = dict.fromkeys([1,2,3]) >>> dict1 {1: None, 2: None, 3: None} #元組 >>> dict1 = dict.fromkeys((1,2,3)) >>> dict1 {1: None, 2: None, 3: None}
-
實例二:
#修改默認值 >>> dict2 = dict.fromkeys([1,2,3,],'test') >>> dict2 {1: 'test', 2: 'test', 3: 'test'} >>> dict2 = dict.fromkeys([1,2,3,],10) >>> dict2 {1: 10, 2: 10, 3: 10}
-
實例三:
#需要注意! >>> dict3 = dict.fromkeys([1,2,3],['one','two','three']) >>> dict3 {1: ['one', 'two', 'three'], 2: ['one', 'two', 'three'], 3: ['one', 'two', 'three']}