python變量類型
python變量不需要類型聲明.
- 基本類型
counter = 100 # 賦值整型變量
miles = 1000.0 # 浮點型
name = "John" # 字符串
- 字符串
s='runnoob'
字符串的索引有2中順序:
- 從左到右索引默認0開始的
- 從右到左索引默認-1開始的
[頭下標:尾下標] 獲取的子字符串包含頭下標的字符,但不包含尾下標的字符。
s='abcdef'
print(s[0]) # 'a'
print(s[1:5]) # 'bcde'
print(s[-1]) # s[-1]='f'
s[0:-1] # 'abcde'
s[1:4:2] # 結果爲'bd',其中s[1:4:2]中的2表示步長
#字符串的+,*
s1='hello'
s2='world'
print(s1+s2) # 'helloworld'
print('ni'+' hao') # 'ni hao'
print('a'*5) # 'aaaaa'
- 需要掌握list,tuple,dict
2.1 list(可變變量)
list1=[2,3,4,5,6]
list1[0] # 2
list1[1]=7 # list1[1]賦值爲7
list1[1:3] # [3,4]
list1[2:] # [4,5,6]
# list中可以是不同的數據類型,如下:
list1 = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
list1 = [123, 'john']
注意: list中append函數和extend函數的區別
list1=[2,3,4]
list2=[1,5,7]
list3=list1.append(list1)
print(list3) # [2,3,4,[1,5,7]]
list4=list1.extend(list2)
print(list4) # [2,3,4,1,5,7]
2.2 tuple元組(不可變變量)
tuple類似於list,要注意tuple和list的不同
t1 = ( 'runoob', 786 , 2.23, 'john', 70.2 )
t1[0] # 'runoob'
t1[1:3] # (786,2.23)
t1[2:] # (2.23,'join',70.2)
t1[2]=10 # 不可,元組不可更改
注意: 要定義一個只有1個元素的tuple,如果你這麼定義:
>>> t = (1)
>>> t
1
定義的不是tuple,是1這個數!這是因爲括號()既可以表示tuple,又可以表示數學公式中的小括號,這就產生了歧義,因此,Python規定,這種情況下,按小括號進行計算,計算結果自然是1。
所以,只有1個元素的tuple定義時必須加一個逗號,,來消除歧義:
>>> t = (1,)
>>> t
(1,)
2.3 dict字典
d1 = {}
d1['one'] = "This is one"
d1[2] = "This is two"
print(d1['one']) # 輸出鍵爲'one' 的值
print(d1[2]) # 輸出鍵爲 2 的值
d2 = {'name': 'john','code':6734, 'dept': 'sales'}
print(d2) # 輸出完整的字典
print(d2.keys()) # 輸出所有鍵
print(d2.values()) # 輸出所有值
print(d2.items())
注意: 遍歷字典的方法,使用d2.items()
d2 = {'name': 'john','code':6734, 'dept': 'sales'}
for k,v in d2.items(): # 這裏必須是d2.items(),不能直接寫d2
print(k,'--->',v)
作業:
請用索引取出下面list的指定元素:
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print(?)
# 打印Python:
print(?)
# 打印Lisa:
print(?)