Python基础回顾基本数据类型

在这篇文章中,主要是对Python做一个较为细致的回顾。

Type

Python中比较常用的几种数据类型包括string,integer以及float。一般通过type()去获得一个变量的数据类型

x = 2.14
type(x) # float

x = 2
type(x) # int

x = '2'
type(x) # str

另外一种数据类型是布尔型变量,boolean

type(True) # bool

int(True) # 1, bool --> int
bool(1) # True, int -->bool

两个符号的差异:///,/表示除法,//表示整除。

String

string类型的变量通常用''或者""表示,string可以看成一个数组,因此可以通过索引得到string中的具体字符。

name = "Michael Jackson"
name[0] # M
name[-1] # n
# 切片操作

name[0 : 4] # 'Mich'
name[::2] # 以2为stride, 提取name中的字符,得到字符串 'McalJcsn'

两个string之间可以直接使用+进行连接,

name1 = 'Mj'
name2 = 'ja'
name = name1 + name2 # Mjja

string中的基本操作:


# 将小写变成大写 upper()
a = "Thriller is the sixth studio album"
b = a.upper() # THRILLER IS THE SIXTH STUDIO ALBUM

# 替换字符串中的字符
a = "Michael Jackson is the best"
b = a.replace('Michael', 'Janet') # Janet Jackson is the best

# 在字符串中寻找另一字符串,find()
# 如存在,可返回首次出现该字符的位置,否则返回-1
name = "Michael Jackson"
name.find('el') # 5, 
name.find('Jasdfasdasdf') #-1

tuples

tuple表示元组,用()表示。里面的元素可以是多种类型。

tuple1 = ("disco",10,1.2 )
type(tuple1) # tuple

元组里的元素可以利用索引值得到

print(tuple1[0]) # disco
print(tuple1[1]) # 10
print(tuple1[2]) # 1.2

# 同样可以使用负数进行索引
tuple1[-1] # 1.2

# 元组拼接
tuple2 = tuple1 + ("hard rock", 10) #('disco', 10, 1.2, 'hard rock', 10)
# 同样的,元组里的元素访问也支持切片
tuple2[0:3] # ('disco', 10, 1.2)
# 使用sorted对元组进行排序,(可排序)
Ratings = (0, 9, 6, 5, 10, 8, 9, 6, 2)
RatingsSorted = sorted(Ratings) #[0, 2, 5, 6, 6, 8, 9, 9, 10]

元组中可嵌套元组,此时访问元组中元素可能涉及到多重索引。

NestedT =(1, 2, ("pop", "rock") ,(3,4),("disco",(1,2)))
print("Element 2, 0 of Tuple: ",   NestedT[2][0]) #pop
print("Element 2, 1 of Tuple: ",   NestedT[2][1]) # rock
print("Element 3, 0 of Tuple: ",   NestedT[3][0]) # 3
print("Element 3, 1 of Tuple: ",   NestedT[3][1]) # 4
print("Element 4, 0 of Tuple: ",   NestedT[4][0]) # disco
print("Element 4, 1 of Tuple: ",   NestedT[4][1]) # (1,2)

List

List列表使用[]来表示,其元素同样可以是多种数据类型。

L = ["Michael Jackson", 10.1, 1982]

列表中元素的访问同样支持正负索引

print('the same element using negative and positive indexing:\n Postive:',L[0],
'\n Negative:' , L[-3]  )
print('the same element using negative and positive indexing:\n Postive:',L[1],
'\n Negative:' , L[-2]  )
print('the same element using negative and positive indexing:\n Postive:',L[2],
'\n Negative:' , L[-1]  )

#the same element using negative and positive indexing:
# Postive: Michael Jackson 
# Negative: Michael Jackson
#the same element using negative and positive indexing:
# Postive: 10.1 
# Negative: 10.1
#the same element using negative and positive indexing:
# Postive: 1982 
# Negative: 1982

List的基本操作

# 使用索引进行访问,支持切片操作
L = ["Michael Jackson", 10.1,1982,"MJ",1]
L[3:5] # ['MJ', 1]

# 使用 extend 给列表增加新元素
L.extend(['pop', 10]) #['Michael Jackson', 10.2, 'pop', 10]

# append, 与extend不同的地方在于,append添加了一个列表在原列表中
L.append(['a','b']) # ['Michael Jackson', 10.2, 'pop', 10, ['a', 'b']]

# del()删除列表中的某个元素
del(L[0]) # [10.2, 'pop', 10, ['a', 'b'], ['a', 'b']]

# split(),以某个分隔符进行分割字符串,默认为空格, 其结果得到一个列表
'hard rock'.split() #['hard', 'rock']
'A,B,C,D'.split(',') # ['A', 'B', 'C', 'D']

Set

Set表示集合,一个集合中的元素是唯一的。一般使用{}表示Set

set1 = {"pop", "rock", "soul", "hard rock", "rock", "R&B", "rock", "disco"} 
# 下面的结果中所有元素均不重复
#{'R&B', 'disco', 'hard rock', 'pop', 'rock', 'soul'}
type(set1) # set

#将list变成set
music_genres = set(["pop", "pop", "rock", "folk rock", "hard rock", "soul", \
                    "progressive rock", "soft rock", "R&B", "disco"])
# {'R&B','disco','folk rock','hard rock','pop','progressive rock','rock','soft rock','soul'}

Set中的基本运算

A = set(["Thriller", "Back in Black", "AC/DC"])

# 使用add()给set增加元素
A.add("NSYNC") # {'AC/DC', 'Back in Black', 'NSYNC', 'Thriller'}
# 使用remove()移除元素
A.remove("NSYNC") #{'AC/DC', 'Back in Black', 'Thriller'}
# 使用in()判断一个元素是否在Set里
"AC/DC" in A # True

类比于数学上的集合,那么Set应该支持取两个Set的交集,并集。


album_set1 = set(["Thriller", 'AC/DC', 'Back in Black'])
album_set2 = set([ "AC/DC", "Back in Black", "The Dark Side of the Moon"])

# 取交集,&, intersection()
intersection = album_set1 & album_set2 # {'AC/DC', 'Back in Black'}
album_set1.intersection(album_set2)  
# 取差集,difference(), 即一个set中有,另外一个set中没有
album_set1.difference(album_set2)  # {'Thriller'}

# 取并集 intersection()
album_set1.union(album_set2)   
# {'AC/DC', 'Back in Black', 'The Dark Side of the Moon', 'Thriller'}

Dictionaries

Dictionary包含键值对,一个典型的字典如下

Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5'): 5, (0, 1): 6}
# {'key1': 1,
# 'key2': '2',
# 'key3': [3, 3, 3],
# 'key4': (4, 4, 4),
# 'key5': 5,
# (0, 1): 6}

# 通过键得到值
Dict["key1"] # 1
Dict[(0, 1)] # 6

# 得到所有的键
Dict.keys()

# 得到所有的值
Dict.values()
原文地址:https://www.cnblogs.com/tingweichen/p/14460740.html