List-like Type

跟串列類似的型別

其實字串str跟串列很像,它是由一個一個的字元組成的。 舉例來說,'apple'可以看成'a'+'p'+'p'+'l'+'e'五個字元組成, 因此,當然可以進行如下操作:

apple = 'apple'
print(apple[1])
print(apple[2])
print(apple[3])
print(apple[0:3])
print(len(apple))
print(apple.index('l'))

但畢竟字串不是串列,所以它並沒有串列所有的方法,如果要知道字串的所有方法,在intellij中,鍵入apple., 編輯器就會提示你有多少函式可以使用。

Tuple 多元組

多元組是一組由各種型別組成的串列,他跟串列很像,但語法與操作如下:

fruits = ('apple', 'banana', 'cherry')
print(fruits[0])
print(fruits[1])
print(fruits[0:2])
print(len(fruits))

# 多元組可以放入許多種不同型別的東西,串列也可以
combination = ('apple', 2, 'cheery')
print(combination)

# list and tuple 可以互相轉換
fruits2 = list(fruits)
print(type(fruits2))
fruits3 = tuple(fruits2)
print(fruits == fruits3)

多元組是用小括弧括起來的,而串列是用中括弧括起來的,多元組與串列的差別是,多元組不能修改其中的值, 如果你有一組一組固定的值是屬於同一個群,那麼可以使用多元組,例如:

people = [('John', 'US', 18), ('Mary', 'England', 30), ('Tom', 'France', 38)]

Last updated

Was this helpful?