設定理解

集合理解類似於列表字典理解 ,但它產生一個集合 ,它是一個獨特元素的無序集合。

Python 2.x >= 2.7

# A set containing every value in range(5):
{x for x in range(5)}
# Out: {0, 1, 2, 3, 4}

# A set of even numbers between 1 and 10:
{x for x in range(1, 11) if x % 2 == 0}
# Out: {2, 4, 6, 8, 10}

# Unique alphabetic characters in a string of text:
text = "When in the Course of human events it becomes necessary for one people..."
{ch.lower() for ch in text if ch.isalpha()}
# Out: set(['a', 'c', 'b', 'e', 'f', 'i', 'h', 'm', 'l', 'o',
#           'n', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y'])

現場演示

請記住,集合是無序的。這意味著集合中結果的順序可能與上述示例中的順序不同。

注意 :自從 python 2.7+以來可以使用集合理解,而不像 2.0 中新增的列表理解。在 Python 2.2 到 Python 2.6 中,set() 函式可以與生成器表示式一起使用以產生相同的結果:

Python 2.x >= 2.2

set(x for x in range(5))
# Out: {0, 1, 2, 3, 4}