在 Python 中遍歷一個集合


在本文中,我們將學習在 Python 3.x 或更早版本中遍歷/遍及一個集合。

這是一個無序的物件集合,沒有重複項。這可以透過將所有元素括在大括號內來實現。我們還可以透過關鍵字“set”進行型別轉換來形成集合。

方法 1 − 使用沒有索引的可迭代物件

示例

set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value in set_inp:
   print(value, end='')

方法 2 − 透過轉換為列表型別使用索引訪問

示例

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(0,len(set_inp)):
   print(set_inp[value], end='')

方法 3 − 使用列舉型別

示例

set_inp = {'t','u','t','o','r','i','a','l','s','p','o','i','n','t'}

# Iterate over the set
for value,char in enumerate(set_inp):
   print(char, end='')

方法 4 − 透過轉換為列表型別使用負索引

示例

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set
for value in range(-len(set_inp),0):
   print(set_inp[value], end='')

上述 4 種方法產生以下輸出。

輸出

plsrainuto

方法 5 − 在轉換為列表型別後使用切片

示例

set_inp = list({'t','u','t','o','r','i','a','l','s','p','o','i','n','t'})

# Iterate over the set

for value in range(1,len(set_inp)):
   print(set_inp[value-1:value], end='')
print(set_inp[-1:])

輸出

['p']['l']['s']['r']['a']['i']['n']['u']['t']['o']

結論

在本文中,我們學習了關於集合資料型別的遍歷。此外,我們還學習了各種實現技術。

更新於: 2020 年 7 月 1 日

2K+ 瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.