3.Python data types

Python data types

# Create a long integer

# 在Python 3裏,只有一種整數類型 int,表示爲長整型,沒有 python2 中的 Long 
# Create a String

pythonStr = "Learning PySpark is fun"
pythonStr
pythonStr[9]
'P'
# find 

pythonStr[9]
pythonStr.find("Py"),pythonStr.find("py")
(9, -1)
# Check String

pythonStr.startswith("Learning"),pythonStr.endswith("fun")
(True, True)

List

pythonList = [2.3,3.4,4.3,2.4,2.3,4.0]
 
pythonList1 = ["a",1]
pythonList1

type(pythonList1),type (pythonList1[0]),type (pythonList1[1])
(list, str, int)
# Sorting a List

pythonList = [2.3,3.4,4.3,2.4,2.3,4.0]
 
pythonList.sort()

print(pythonList)

pythonList.sort(reverse=True)

print(pythonList)
[2.3, 2.3, 2.4, 3.4, 4.0, 4.3]
[4.3, 4.0, 3.4, 2.4, 2.3, 2.3]

Tuple

# Creating a Tuple

pythonTuple = (2.0,9,"a",True,"a")

type(pythonTuple), pythonTuple[2]
(tuple, 'a')
# Getting index of an element of a Tuple.

print(pythonTuple.index('a'))

# Counting occurrence of a Tuple element.

print(pythonTuple.count("a"))
2
2

Set

# Creating a Set.

pythonSet = {'Book','Pen','NoteBook','Pencil','Book'}
pythonSet
{'Book', 'NoteBook', 'Pen', 'Pencil'}
# Adding a new element to a set.

pythonSet.add("Eraser")
pythonSet
{'Book', 'Eraser', 'NoteBook', 'Pen', 'Pencil'}
# Union on Sets.

pythonSet1 = {'NoteBook','Pencil','Diary','Marker'}
pythonSet1
pythonSet.union(pythonSet1)
{'Book', 'Diary', 'Eraser', 'Marker', 'NoteBook', 'Pen', 'Pencil'}
# intersection on Sets.

pythonSet.intersection(pythonSet1)
{'NoteBook', 'Pencil'}

Dict

# Create a dictionary

pythonDict = {'item1':'Pencil','item2':'Pen', 'item3':'NoteBook'}


pythonDict['item1'], pythonDict.get('item1'), pythonDict.get('item4')
('Pencil', 'Pencil', None)

Lambda function

# Lambda Function 

isEvenInteger = lambda ourNum : ourNum%2 == 0

isEvenInteger(4),isEvenInteger(5)

(True, False)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章