Home  >  Article  >  Backend Development  >  Detailed introduction to python types (type)

Detailed introduction to python types (type)

零下一度
零下一度Original
2017-06-27 09:26:414406browse

Empty (None)

None can be used to indicate that the value of a certain variable is missing, similar to null in other languages.

Like other null values: 0, [] and empty string, Boolean variables give False instead of True.

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

The result is:

None got interpreted as False

When a function does not return any value, it returns None:

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

The result is:

##
Hi
None
View Code
Dictionaries

A dictionary is a data structure that assigns keys to values. A list can be thought of as a dictionary with some range of integer keys.

Dictionaries can be indexed like lists, using square brackets, except that the square brackets are no longer subscripts, but keywords

ages={"Dave":24,"Mary":42,"John":58}print(ages["Dave"])print(ages["Mary"])
The result is:

24
42
View Code
An error will occur when indexing a keyword that is not a dictionary. Dictionaries can store values ​​of any data type. An empty dictionary is "{}".

The keywords of the dictionary cannot be changed. Using a mutable object as a dictionary key will produce a TypeError.

bad_dict={
    [1,2,3]:"one two three"}
The result is:

TypeError: unhashable type: 'list'
View Code
Dictionary Functions (Dictionary Functions)

Dictionary keys can be assigned different values. If there is no keyword, create a new keyword:

squares={1:1,2:4,3:"error",4:16}
squares[8]=64squares[3]=9print(squares)
The result is:

{1: 1, 2: 4, 3: 9, 4: 16, 8: 64}
View Code
Check whether a keyword exists in the dictionary with in or not in just like in the list.

nums={1:"one",2:"two",3:"three"}print(1 in nums)print("three"in nums)print(4 not in nums)
The result is:

True
False
True
View Code
get It is a very easy-to-use dictionary method that plays the same role as an index, but if the keyword is not found in the dictionary, it will return None instead of the error

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 The second parameter means that if the keyword cannot be found, this value will be returned.

The result is:

##
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

Tuples are very similar to lists, but they cannot be changed. You can create a new tuple with parentheses, or without...:

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

 

The above is the detailed content of Detailed introduction to python types (type). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn