Lists:列表
- [ ]:square brackets用來存放一系列單一變數(store multiple items in a single variable.)
- 前面不用放等號
- 用逗點(,)隔開
- 有順序
# In Python, a list is a collection of items that are ordered and have specific index
# A list is defined using square brackets [], we separate elements in a list by commas
# A list can have items with various datatypes such as integers, floats, or strings
# Let's define a list of U.S., European, Asian and African companies
my_companies=["Allple","Samsung","Alibaba","Nova","Naspers"]
indexing:access specific elements in Python lists
- 在[]輸入編號用來檢索指定的
my_companies[0]是指“Apple”
Lists Slicing:從List中存取多的元素(access a range of elements within the list)
[n:m]:存取從第n個開始,但不包含# We can use list slicing to obtain more than one element from a list
# Obtain elements starting from index 1 up to and not including element with index 4
#存取"Samsung","Alibaba","Nova"
my_companies[1:4]
[n:]:存取從第n個開始到結束
# Obtain elements starting from index 2 to end
my_companies[2:]
[:]:存取全部
# Print out all elements start to end
my_companies[:]
PRACTICE OPPORTUNITY
Assume that you work as a financial analyst and you decided to list 9 dividend-paying companies in the U.S. in a Python list named “dividend_companies” as shown below:
dividend_companies = ['Pioneer Natural Resources Co. (ticker: PXD)', 'Lumen Technologies Inc. (LUMN)', 'Altria Group Inc. (MO)', 'Vornado Realty Trust (VNO)', 'Devon Energy Corp. (DVN)', 'AT&T Inc. (T)', 'Simon Property Group Inc. (SPG)', 'Verizon Communications Inc. (VZ)', 'Kinder Morgan Inc. (KMI)']
- Print the first, second and fourth elements individually
- Print the last element using 3 different methods (external research is required)
- Print all elements in the list, first 3 elements, and last three elements
#Print the first, second and fourth elements individually
print(dividend_companies[0])
print(dividend_companies[1])
print(dividend_companies[3])
#Print the last element using 3 different methods (external research is required)
#1 指定最後一個
print(dividend_companies[8])
#2.先用len抓出有幾個參數,該數字減一
len(dividend_companies)
print(dividend_companies[len(dividend_companies)-1])
#3.
list.reverse(dividend_companies)
print(dividend_companies[0])
#Print all elements in the list, first 3 elements, and last three elements
print(dividend_companies[:])
print(dividend_companies[0:3])
print(dividend_companies[6:])
你好,我是蔡至誠PG,任職於《阿爾發證券投顧》,《我畢業五年,用ETF賺到400萬》作者,《提早五年退休:PG 財經個人財務調配術》講師。