搜索
首页后端开发Python教程关于python类型(type)的详细介绍

关于python类型(type)的详细介绍

Jun 27, 2017 am 09:26 AM
type类型

空(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

get是一个非常好用的字典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
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具