跳轉到

2.2 資料型態與轉換

Numbers

整數 浮點 數複數

# Output: <class 'int'>
print(type(5))

# Output: <class 'float'>
print(type(5.0))

# Output: <class 'complex'>
c = 5 + 3j
print(type(c))

Lists

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes
my_list = [1, "Hello", 2.3]

# nested list
my_list = ["mouse", [8, 4, 6]]

List - index

my_list = ['h','e','l','l','o']

print(my_list[0]) # Output: h
print(my_list[1]) # Output: e

# my_list[5.0] # Error! Only integer can be used for indexing
n_list = ["Happy", [2,0,1,8]] # Nested List
print(n_list[1][3]) # Output: 8

List - negative indexing

my_list = ['p','r','o','b','e']

print(my_list[-1]) # Output: e
print(my_list[-5]) # Output: p

List - slicing(切片)

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(my_list[2:5]) # elements 3rd to 5th

## [2, 3, 4]
print(my_list[:-5]) # elements beginning to 4th

## [0, 1, 2, 3]
print(my_list[5:]) # elements 6th to end

## [5, 6, 7, 8]
print(my_list[:]) # elements beginning to end
## [0, 1, 2, 3, 4, 5, 6, 7, 8]

print(my_list[::3]) # slice a parent list with a step length 取全部間格3
## [0, 3, 6]

Built-in List Methods

num_list = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8]

# append() is used to add an element at the end of the list.
num_list.append(9)

# remove() takes a single element as an argument and removes itfrom the list.
num_list.remove(9)
# index() is used to find the index value of a particular element.
num_list.index(5)

# pop() takes a single argument (index) and removes the element present at that index from the list.
result = num_list.pop(7)

print(result) # 6
print(num_list) # [0, 0, 1, 2, 3, 4, 5, 7, 8]

Tuples

Tuples元素不能修改

# empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)

Strings

# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)

可以利用索引值取得內容

my_str = 'Hello World!'
print('my_str = ', my_str) # my_str = Hello World!

# first character, last character
print(my_str[0]) # H
print(my_str[-1]) # !

# slicing 3nd to 5th character
print(my_str[2:5]) # llo

字串串連

str1 = 'Hello'
str2 = 'World!'

# using +
print(str1 + str2) # HelloWorld!

# using *
print(str1 * 3) # HelloHelloHello

Built-in Strings Methods

my_string = "hello world"

print(my_string.find("he")) # Output: 0
print(my_string.capitalize()) # Output: Hello world
print(my_string.upper()) # Output: HELLO WORLD
print(my_string.endswith("d")) # Output: True

print(my_string.split(" ")) # Output: ['hello', 'world']

print(my_string.replace("hello", "Nihao")) # Output: Nihao world

Sets

無序資料集合且不能重複無法更改

# set of integers
my_set = {1, 2, 3}
print(my_set) # {1, 2, 3}
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set) # {'Hello', 1.0, (1, 2, 3)}

連集與交集

# mathematical set operations
set_1 = set(['s', 'p', 'a','m'])
set_2 = set(['h','a','m'])
# union, intersection
print(set_1 | set_2) # {'h', 'p', 'm', 's', 'a'}
print(set_1 & set_2) # {'a', 'm'}
# symmetric difference
print(set_1 - set_2) # {'p', 's'}

Dictionary

一個key對應一個value

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {1: 'a', 2: 'b'}

# dictionary with mixed keys
my_dict = {'name': 'Tom', 1: 23}

修改dictionary內容

# Another define
my_dict = dict()

# add elements
my_dict['One'] = '1'
my_dict['OneTwo'] = 12
print (my_dict) # {'One': '1', 'OneTwo': 12}
# update value
my_dict['One'] = 111
print (my_dict) # {'One': 111, 'OneTwo': 12}

使用zip將兩個list合併成dictionary

# Merge two lists to a dictionary.
names = ['One', 'Two', 'Three', 'Four', 'Five']
numbers = [1, 2, 3, 4, 5]
merged_dict = dict(zip(names, numbers))

print(merged_dict) # {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5}

Dictionary Methods

my_dict = {'name':'Jack', 'age': 16, 'gender':'man'}
# remove a particular item
print(my_dict.pop('gender')) # man
print(my_dict) # {'name': 'Jack', 'age': 16}
# Returns view of dictionary's (key, value) pair
print(my_dict.items()) # [('name', 'Jack'), ('age', 16)]
# Return a new view of the dictionary's keys.
print(my_dict.keys()) # ['name', 'age']
# remove all items
my_dict.clear()
print(my_dict) # {}