新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonset()
內(nèi)置函數(shù)集()用于在 python 中創(chuàng)建集合。該集合是存儲多個數(shù)據(jù)的單個變量,它應(yīng)該是無序的和無索引的,并且不能允許重復(fù)的值。

**set(iterable)** #where iterable can be string,tuple,set,dictionary,etc
設(shè)置()參數(shù):
它只需要一個參數(shù)。使用{ }我們不能創(chuàng)建空集它會創(chuàng)建一個空字典,所以我們使用set()來創(chuàng)建一個空集。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 可迭代的 | 序列(字符串、元組等。)或收藏(集、字典等。)或要轉(zhuǎn)換成集合的迭代器對象 | 可選擇的 |
設(shè)置()返回值
我們不能在集合創(chuàng)建后修改它們。
| 投入 | 返回值 | | 沒有參數(shù) | 空集 | | 可迭代參數(shù) | 從給定的可迭代表構(gòu)造的集合 |
Python 中set()方法的示例
示例 1:如何從字符串、元組、列表和范圍創(chuàng)建集合
# empty set
print(set())
# from string
print(set('Python'))
# from tuple
print(set(('a', 'e', 'i', 'o', 'u')))
# from list
print(set(['a', 'e', 'i', 'o', 'u']))
# from range
print(set(range(5)))
輸出:
set()
{'P', 'o', 't', 'n', 'y', 'h'}
{'a', 'o', 'e', 'u', 'i'}
{'a', 'o', 'e', 'u', 'i'}
{0, 1, 2, 3, 4}
示例 2:如何從另一個集合、字典和凍結(jié)集合創(chuàng)建集合
# from set
print(set({'a', 'e', 'i', 'o', 'u'}))
# from dictionary
print(set({'a':1, 'e': 2, 'i':3, 'o':4, 'u':5}))
# from frozen set
frozen_set = frozenset(('a', 'e', 'i', 'o', 'u'))
print(set(frozen_set))
輸出:
{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'i', 'e', 'u'}
{'a', 'o', 'e', 'u', 'i'}
示例 3:如何為自定義可迭代對象創(chuàng)建set()
class PrintNumberlist:
def __init__(self, max):
self.max = max
def __iter__(self):
self.num = 0
return self
def __next__(self):
if(self.num >= self.max):
raise StopIteration
self.num += 1
return self.num
# print_num is an iterable
print_number = PrintNumberlist(5)
# creating a set
print(set(print_number))
輸出:
{1, 2, 3, 4, 5} 名稱欄目:創(chuàng)新互聯(lián)Python教程:Pythonset()
文章源于:http://m.fisionsoft.com.cn/article/coieogg.html


咨詢
建站咨詢
