首頁  >  文章  >  後端開發  >  關於python類型(type)的詳細介紹

關於python類型(type)的詳細介紹

零下一度
零下一度原創
2017-06-27 09:26:414332瀏覽

空(None)

None可以用來表示某一個變數的值缺失,類似其他語言的null。

像其他的空值:0,[]和空的string,布林變數給的是False而不是True。

if None:print("None got interpreted as True")else:print("None got interpreted as False")

結果是:

None got interpreted as False

#當一個函數沒有傳回任何值時,就會傳回None:

def some_func():print("Hi")
var=some_func()print(var)

結果是:

Hi
None
#View Code

字典(Dictionaries)

字典是一種賦予值關鍵字的資料結構。列表可以被看做一個有著某種範圍的整數關鍵字的字典。

字典可以像列表一樣索引,用方括號,只不過方括號裡不在是下標,而是關鍵字

ages={"Dave":24,"Mary":42,"John":58}print(ages["Dave"])print(ages["Mary"])
結果是:
24
42
View Code

#索引一個不是字典的關鍵字會出現錯誤,字典可以儲存任何資料類型的值,空的字典為“{}”。

字典的關鍵字是不能改的。使用一個可以更改的object當做字典的關鍵字會產生類型錯誤(TypeError)。

bad_dict={
    [1,2,3]:"one two three"}
結果是:
#
TypeError: unhashable type: 'list'
View Code

字典函數(Dictionary Functions)

字典的關鍵字可以被賦予不同的值。如果沒有關鍵字,那就新建一個關鍵字:

squares={1:1,2:4,3:"error",4:16}
squares[8]=64squares[3]=9print(squares)
結果是:
{1: 1, 2: 4, 3: 9, 4: 16, 8: 64}

## View Code

查看字典中是否存在某個關鍵字用in或not in 就像在列表中一樣。
nums={1:"one",2:"two",3:"three"}print(1 in nums)print("three"in nums)print(4 not in nums)
結果是:

True
False
True
View Code
是一個非常好用的字典method,起的作用和索引一樣,但是如果在字典中找不到關鍵字,就會回傳None,而不是錯誤######
paris={1:"apple","orange":[2,3,4],
    True:False,
    None:"True"}print(paris.get("orange"))print(paris.get(7))print(paris.get(12345,"not in dictionary"))
#######get的第二個參數的意思是找不到關鍵字就回傳這個值。 ######結果是:###############
paris={1:"apple","orange":[2,3,4],
    True:False,
    None:"True"}print(paris.get("orange"))print(paris.get(7))print(paris.get(12345,"not in the dicrionary"))
#######View Code#########元組(Tuples)### ###元組和列表很像,但他們是不能被更改的,用括號就能新建一個元組,不用也可以…:######
words=("spam","eggs","sausages",)
######
words="spam","eggs","sausages",
###

空元组用()新建。

元组的运行速度比列表快

其他使用方法和列表类似。

列表切片(List Slices)

列表切片是一种检索列表值的高级方法。基本的切片方法是用两个被冒号分开的整数来索引列表。这样可以从旧列表返回一个新列表。

squares=[0,1,4,9,16,25,36,49,64,81]print(squares[2:6])print(squares[3:8])print(squares[0:1])

结果是:

[4, 9, 16, 25]
[9, 16, 25, 36, 49]
[0]
View Code

跟range的参数相似,第一的下标的值会包括,但不包括第二个下标的值。

如果第一个下标省略,默认从头开始,

如果第二个下标省略,默认到结尾结束。

切片同样可以用于元组。

切片也有第三个参数,决定了步长。第一二个分别决定了开头与结尾。

squares=[0,1,4,9,16,25,36,49,64,81]
print(squares[:6:2])
print(squares[3::3])
print(squares[::3])

结果是:

[0, 4, 16]
[9, 36, 81]
[0, 9, 36, 81]

参数是复数的话就倒着走。-1是倒数第一,-2是倒数第二,第三个参数为负就会倒着切,这时候第一个参数和第二个参数就要倒着看了,也就是第二个参数变成了开始,第一个变成了结尾(因此-1会使整个列表倒序)

squares=[0,1,4,9,16,25,36,49,64,81]print(squares[:-1])print(squares[::-3])print(squares[-3::2])

结果是:

[0, 1, 4, 9, 16, 25, 36, 49, 64]
[81, 36, 9, 0]
[49, 81]
View Code

列表解析(List Comprehensions)

这是一种快速创建遵循某些规则的列表的方法:

cubes=[i**3 for i in range(5)]print(cubes)

结果是:

[0, 1, 8, 27, 64]
View Code

也可以包含if statement 加强限定条件。

evens=[i**2 for i in range(10) if i**2 % 2==0]print(evens)

结果是:

[0, 4, 16, 36, 64]
View Code
evens=[i**2 for i in range(10) if i**2 % 2==0]print(evens)

结果是:

[0, 4, 16, 36, 64]
View Code

range的范围过大会超出内存的容量引发MemoryError

String Formatting

为了使string和non-string结合,可以把non-string转化为string然后再连起来。

string formatting提供了一种方式,把non-string嵌入到string里,用string的format method来替换string里的参数。

nums=[4,5,6]
msg="Numbers:{0} {1} {2}".format(nums[0],nums[1],nums[2])print(msg)

format里的参数和{}里的参数是对应的。{}的参数是format()里参数的下标

参数被命名这种情况也是可以的:

a="{x},{y}".format(x=5,y=12)print(a)

结果是:

5,12
View Code

Useful Functions

Python 内置了许多有用的函数

join ,用一个string充当分隔符把一个由string组成的列表连起来。

print(",".join(["spam","eggs","ham"]))

结果是:

spam,eggs,ham
View Code

replace,用一个string 取代另一个。

print("Hello ME".replace("ME","world"))

结果是:

Hello world
View Code

startwith和endwith,判断是否是由……开头或结束:

print("This is a sentence.".startswith("This"))print("This is a sentence.".endswith("sentence."))

结果是:

True
True
View Code

lower和upper可以改变string的大小写

print("This is A sentence.".upper())print("THIS IS a SENTENCE..".lower())

结果是:

THIS IS A SENTENCE.
this is a sentence.
View Code

split的作用于join 相反,他可以按某个string为分隔符将一串string分开并成为列表的形式。

print("apple,eggs,banana".split(","))

结果是:

['apple', 'eggs', 'banana']

 有关数学的一些函数有:最大值max,最小值min,绝对值abs,约等数round(第二个参数可以决定保留几位小数),对列表里的数求和用sum等:

print(min(1,2,3,4,5,6,7))print(max(1,2,3,4,5,6,7))print(abs(-98))print(round(78.632453434,4))print(sum([2.12121,23232323]))

结果是:

1
7
98
78.6325
23232325.12121
View Code

all和any可以把列表当成参数,然后返回True或 False,

nums=[55,44,33,22,11]if all([i <56 for i in nums]):print("All smaller than 56.")

 

nums=[55,44,33,22,11]if any([i <22 for i in nums]):print("at least one is smaller than 22.")

all和any的区别是,all需要所有的值都满足,any只需要有一个满足就行了。

枚举(enumerate),字面意思,把列表中的值按顺序一个一个列出来。

nums=[55,44,33,22,11]for v in enumerate(nums):print(v)

结果是:

(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
View Code

 

以上是關於python類型(type)的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn