Table of Contents
Empty (None)
Tuples are very similar to lists, but they cannot be changed. You can create a new tuple with parentheses, or without...:
列表切片(List Slices)
列表解析(List Comprehensions)
String Formatting
Useful Functions
Home Backend Development Python Tutorial Detailed introduction to python types (type)

Detailed introduction to python types (type)

Jun 27, 2017 am 09:26 AM
type type

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.

1

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

Copy after login

The result is:

1

None got interpreted as False

Copy after login

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

1

2

def some_func():print("Hi")

var=some_func()print(var)

Copy after login

The result is:

##

1

2

Hi

None

Copy after login
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

1

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

Copy after login
The result is:

1

2

24

42

Copy after login
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.

1

2

bad_dict={

    [1,2,3]:"one two three"}

Copy after login
The result is:

1

TypeError: unhashable type: 'list'

Copy after login
View Code
Dictionary Functions (Dictionary Functions)

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

1

2

squares={1:1,2:4,3:"error",4:16}

squares[8]=64squares[3]=9print(squares)

Copy after login
The result is:

1

{1: 1, 2: 4, 3: 9, 4: 16, 8: 64}

Copy after login
View Code
Check whether a keyword exists in the dictionary with in or not in just like in the list.

1

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

Copy after login
The result is:

1

2

3

True

False

True

Copy after login
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

1

2

3

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"))

Copy after login
get The second parameter means that if the keyword cannot be found, this value will be returned.

The result is:

##

1

2

3

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"))

Copy after login
View Code
Tuples

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

1

words=("spam","eggs","sausages",)

Copy after login

1

words="spam","eggs","sausages",

Copy after login

空元组用()新建。

元组的运行速度比列表快

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

列表切片(List Slices)

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

1

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

Copy after login

结果是:

1

2

3

[4, 9, 16, 25]

[9, 16, 25, 36, 49]

[0]

Copy after login
View Code

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

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

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

切片同样可以用于元组。

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

1

2

3

4

squares=[0,1,4,9,16,25,36,49,64,81]

print(squares[:6:2])

print(squares[3::3])

print(squares[::3])

Copy after login

结果是:

1

2

3

[0, 4, 16]

[9, 36, 81]

[0, 9, 36, 81]

Copy after login

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

1

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

Copy after login

结果是:

1

2

3

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

[81, 36, 9, 0]

[49, 81]

Copy after login
View Code

列表解析(List Comprehensions)

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

1

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

Copy after login

结果是:

1

[0, 1, 8, 27, 64]

Copy after login
View Code

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

1

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

Copy after login
Copy after login

结果是:

1

[0, 4, 16, 36, 64]

Copy after login
Copy after login
View Code

1

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

Copy after login
Copy after login

结果是:

1

[0, 4, 16, 36, 64]

Copy after login
Copy after login
View Code

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

String Formatting

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

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

1

2

nums=[4,5,6]

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

Copy after login

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

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

1

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

Copy after login

结果是:

1

5,12

Copy after login
View Code

Useful Functions

Python 内置了许多有用的函数

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

1

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

Copy after login

结果是:

1

spam,eggs,ham

Copy after login
View Code

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

1

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

Copy after login

结果是:

1

Hello world

Copy after login
View Code

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

1

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

Copy after login

结果是:

1

2

True

True

Copy after login
View Code

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

1

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

Copy after login

结果是:

1

2

THIS IS A SENTENCE.

this is a sentence.

Copy after login
View Code

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

1

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

Copy after login

结果是:

1

['apple''eggs''banana']

Copy after login

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

1

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]))

Copy after login

结果是:

1

2

3

4

5

1

7

98

78.6325

23232325.12121

Copy after login
View Code

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

1

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

Copy after login

 

1

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

Copy after login

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

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

1

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

Copy after login

结果是:

1

2

3

4

5

(0, 55)

(1, 44)

(2, 33)

(3, 22)

(4, 11)

Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to change network type to private or public in Windows 11 How to change network type to private or public in Windows 11 Aug 24, 2023 pm 12:37 PM

Setting up a wireless network is common, but choosing or changing the network type can be confusing, especially if you don't know the consequences. If you're looking for advice on how to change the network type from public to private or vice versa in Windows 11, read on for some helpful information. What are the different network profiles in Windows 11? Windows 11 comes with a number of network profiles, which are essentially sets of settings that can be used to configure various network connections. This is useful if you have multiple connections at home or office so you don't have to set it all up every time you connect to a new network. Private and public network profiles are two common types in Windows 11, but generally

Solve Ubuntu mounting mobile hard disk error: unknown file system type exfat Solve Ubuntu mounting mobile hard disk error: unknown file system type exfat Jan 05, 2024 pm 01:18 PM

An error occurs when ubuntu mounts a mobile hard disk: mount: unknownfilesystemtype'exfat'. The processing method is as follows: Ubuntu13.10 or install exfat-fuse: sudoapt-getinstallexfat-fuseUbuntu13.04 or below sudoapt-add-repositoryppa:relan/exfatsudoapt-getupdatesudoapt-getinstallfuse- exfatCentOS Linux mount exfat format USB disk error solution to load extfa in CentOS

What are the uses of the Type keyword in Go? What are the uses of the Type keyword in Go? Sep 06, 2023 am 09:58 AM

The usage of the Type keyword in Go includes defining new type aliases or creating new structure types. Detailed introduction: 1. Type alias. Use the "type" keyword to create an alias for an existing type. This alias does not create a new type, but only provides a new name for the existing type. Type aliases can improve code. The readability of the code makes the code clearer; 2. Structure type. Use the "type" keyword to create a new structure type. The structure is a composite type that can be used to define custom types containing multiple fields. etc.

Implementing dynamic arrays in Python: from beginner to proficient Implementing dynamic arrays in Python: from beginner to proficient Apr 21, 2023 pm 12:04 PM

Part 1 Let’s talk about the nature of Python sequence types. In this blog, let’s talk about Python’s various “sequence” classes and the three built-in commonly used data structures – list, tuple and character. The nature of the string class (str). I don’t know if you have noticed it, but these classes have an obvious commonality. They can be used to save multiple data elements. The most important function is: each class supports subscript (index) access to the elements of the sequence, such as using SyntaxSeq[i]​. In fact, each of the above classes is represented by a simple data structure such as an array. However, readers familiar with Python may know that these three data structures have some differences: for example, tuples and strings cannot be modified, while lists can.

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

What is the type of return value of Golang function? What is the type of return value of Golang function? Apr 13, 2024 pm 05:42 PM

Go functions can return multiple values ​​of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of ​​a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

Best practices for type hints in Python Best practices for type hints in Python Apr 23, 2023 am 09:28 AM

It’s great to use dynamic language for a while, and the code is reconstructed in the crematorium. I believe you must have heard this sentence. Like unit testing, although it takes a small amount of time to write code, it is very worthwhile in the long run. This article shares how to better understand and use Python's type hints. 1. Type hints are only valid at the syntax level. Type hints (introduced since PEP3107) are used to add types to variables, parameters, function parameters, and their return values, class properties, and methods. Python's variable types are dynamic and can be modified at runtime to add type hints to the code. It is only supported at the syntax level and has no impact on the running of the code. The Python interpreter will ignore the type hints when running the code. Therefore the type

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

See all articles