元組
從語法上講,元組是以逗號分隔的值列表:
t = 'a', 'b', 'c', 'd', 'e'
雖然沒有必要,但通常將元組括在括號中:
t = ('a', 'b', 'c', 'd', 'e')
使用括號建立一個空元組:
t0 = ()
type(t0) # <type 'tuple'>
要建立具有單個元素的元組,你必須包含最終的逗號:
t1 = 'a',
type(t1) # <type 'tuple'>
請注意,括號中的單個值不是元組:
t2 = ('a')
type(t2) # <type 'str'>
要建立單例元組,必須使用尾隨逗號。
t2 = ('a',)
type(t2) # <type 'tuple'>
請注意,對於單例元組,建議使用括號 (參見尾隨逗號的 PEP8 )。此外,尾隨逗號後沒有空格(請參閱空白處的 PEP8 )
t2 = ('a',) # PEP8-compliant
t2 = 'a', # this notation is not recommended by PEP8
t2 = ('a', ) # this notation is not recommended by PEP8
另一種建立元組的方法是內建函式 tuple
。
t = tuple('lupins')
print(t) # ('l', 'u', 'p', 'i', 'n', 's')
t = tuple(range(3))
print(t) # (0, 1, 2)
這些例子基於 Allen B. Downey 的“ Think Python ”一書中的材料。