Python 入門學習 -----變數及基礎型別(元組,列表,字典,集合)

金少輝發表於2015-01-06

Python的變數和資料型別
1 、python的變數是不需要事先定義資料型別的,可以動態的改變
2、 Python當中一切皆物件,變數也是一個物件,有自己的屬性和方法
來檢視變數的型別:變數名.class
呼叫變數的方法:變數名.方法()

  #!/bin/env python  
    #coding:utf-8

#type 列印出資料的型別

print type(1)
print type(1.0)

print type("helloworld")

#虛數 如12j 
a = 12j + 1
print a
print type(a)

# 除法和求餘數
print "5 / 3 = %d" % ( 5 / 3)
print "5 %% 3 = %d" %( 5 % 3)

#進位制數字列印
print "%d,%o,%x" %(10,10,10)

#檢視變數的型別
a = "hello  world"
print a.__class__
#呼叫變數的方法
print a.split()
  1. Tuple(元組)

    #!/bin/env python
    #coding:utf-8
    #除了字串和數值之外,Python還提供了另外4中重要的基本型別: #元組、列表、集合和字典。

    #元組(tuple) :不可更改的資料序列
    
    
    a = ("first","second","third")
    
    
    #輸出元組
    print (a)
    #列印元組的長度
    print ("a len : %d" % len(a))
    #遍歷元組
    print ("%s %s %s" % (a[0],a[1],a[2]))
    #元組中的一個元素被另一個元組引用
    b = (a,"four")
    print (b)
    print("%s %s %s %s" % (b[0][0],b[0][1],b[0][2],b[1]))
    
    
    # 元組可以包含各種型別的資料,但是在建立之後,就不能再改變
    #元組是不可變的。(字串在建立之後也是不可變的,那些看起來改變
    #他們的操作實際上建立了新的字串)
    #下面的書寫將會報錯
    a[1]  = 3
    
  2. 列表 ---可更改資料的值
    Python

    #!/bin/env python
    #coding:utf-8

    #列表---可更改資料的內容
    list = ["coffee","tea","toast"]
    
    
    #list 長度
    print ("list len is %d" %  (len(list)))
    
    
    #列印list數值
    print ("%s,%s,%s" % (list[0],list[1],list[2]))
    
    
    #修改list[2]的數值
    list[len(list) - 1] = "sausages"
    print ("list[2] is %s" % (list[2]))
    
    
    #list 追加
    list.append("waffles")
    print ("list[%d] is %s" % (len(list) - 1,list[len(list) - 1]))
    
    
    #list 一次性追加多個元素
    list.extend(["juice","decaf"])
    
    
    print(list)
    
  3. 字典--
    python

    #!/bin/env python
    #coding:utf-8
    
    
    #字典---以名稱索引的分組資料
    dict = {}#空字典
    print (dict)
    
    
    dict["a"] = "1"
    dict["b"] = "2"
    
    
    print (dict)
    
    
    #從字典裡獲得它所有的鍵
    key=dict.keys()
    print (list(key))
    #列印鍵和值
    print ("key[%s] : value[%s]" % (key[0],dict.get(key[0])))
    #從字典裡獲得它所有的值
    value=dict.values()
    print (list(value))
    
    
    #字典的工作原理是每個鍵是不同的(不可以有完全相同的兩個鍵)
    #但是可以有多個重複的值
    
  4. 集合

python
#!/bin/env python
#coding:utf-8

#集合 是不包括重複資料的資料集合
list = ['a','b','a','a','b','b']

print ("list is %s" % (list))
print ("set is %s " % (set(list)))

點選投票 =我已參加2014“CSDN部落格之星”的評選,如我的文章對您有幫助,請給我投上寶貴的一票。在此,感謝各位的支援。

相關文章