Table of Contents
Basic data types
Numeric type
Container type
String
自定义类型
Home Backend Development Python Tutorial Analyze examples of four main data types in Python

Analyze examples of four main data types in Python

May 09, 2023 pm 09:16 PM
python

Basic data types

Numeric type

The data in Python are all objects, such as the well-known int integer object, float double precision floating point type, bool logical object, they are all is a single element. Give two examples.

Prefix with 0x to create a hexadecimal integer:

0xa5 # 等于十进制的 165
Copy after login

Use e to create a floating point number represented in scientific notation:

1.05e3 # 1050.0
Copy after login

Container type

A container object that can accommodate multiple elements. Commonly used ones include: list list object, tuple tuple object, dict dictionary object, and set collection object. Python defines these types of variables with a very concise syntax.

Examples are as follows.

Use a pair of square brackets [] to create a list variable:

lst = [1,3,5] # list 变量
Copy after login

As can be seen from the diagram, the container on the right is open-loop, which means that the container can Adding and deleting elements in:

Analyze examples of four main data types in Python

Use a pair of brackets () to create a tuple object:

tup = (1,3,5) # tuple 变量
Copy after login

As shown in the diagram , the container on the right is closed, which means that once a tuple is created, elements cannot be added or deleted from the container:

Analyze examples of four main data types in Python

But it should be noted that tuples containing a single element A comma must be left behind to be interpreted as a tuple.

tup = (1,) # 必须保留逗号
Copy after login

Otherwise it will be considered the element itself:

In [14]: tup=(1)
   ...: print(type(tup)) 
<class &#39;int&#39;>
Copy after login

Use a pair of curly braces {} and use a colon : to create a dict object:

dic = {&#39;a&#39;:1, &#39;b&#39;:3, &#39;c&#39;:5} # dict变量
Copy after login

The dictionary is a hash table. The following diagram vividly expresses the "shape" of the dictionary.

Analyze examples of four main data types in Python

Use only a pair of curly braces {} to create a set object:

s = {1,3,5} # 集合变量
Copy after login

Python container type, list, dict , tuple, set, etc. can easily implement powerful functions. Here are a few cases.

1. Find the average

After removing a minimum value and a maximum value in the list, calculate the average of the remaining elements.

def score_mean(lst):
   lst.sort()
   lst2=lst[1:-1]
   return round((sum(lst2)/len(lst2)),1)

lst=[9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]
score_mean(lst) # 9.1
Copy after login

Code execution process, animation demonstration:

Analyze examples of four main data types in Python

2. Print 99 multiplication table

Print out the following The multiplication table in the format:

1*1=1
1*2=2   2*2=4
1*3=3   2*3=6   3*3=9
1*4=4   2*4=8   3*4=12  4*4=16
1*5=5   2*5=10  3*5=15  4*5=20  5*5=25
1*6=6   2*6=12  3*6=18  4*6=24  5*6=30  6*6=36
1*7=7   2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49
1*8=8   2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64
1*9=9   2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81
Copy after login

has 10 rows in total. The j-th column of the i-th row is equal to: j*i, where:

  • i Value range: 1<=i<=9

  • j Value range: 1<=j<=i

According to the language description of "example analysis", it is converted into the following code:

In [13]: for i in range(1,10):
   ...:     for j in range(1,i+1):
   ...:         print(&#39;%d*%d=%d&#39;%(j,i,j*i),end=&#39;\t&#39;)
   ...:     print()
Copy after login

3. Sample sampling

Use sample sampling , the following example randomly samples 10 samples from 100.

from random import randint,sample
lst = [randint(0,50) for _ in range(100)]
print(lst[:5])# [38, 19, 11, 3, 6]
lst_sample = sample(lst,10)
print(lst_sample) # [33, 40, 35, 49, 24, 15, 48, 29, 37, 24]
Copy after login

String

Note that there is no character type (char) like C in Python, and all characters or strings are unified into str objects. For example, the type of a single character c is also str.

The str type will be frequently used. Let’s first list 5 frequently used methods.

strip is used to remove spaces before and after a string:

In [1]: &#39;  I love python\t\n  &#39;.strip()
Out[1]: &#39;I love python&#39;
Copy after login

replace is used to replace strings:

In [2]: &#39;i love python&#39;.replace(&#39; &#39;,&#39;_&#39;)
Out[2]: &#39;i_love_python&#39;
Copy after login

join is used to merge strings:

In [3]: &#39;_&#39;.join([&#39;book&#39;, &#39;store&#39;,&#39;count&#39;])
Out[3]: &#39;book_store_count&#39;
Copy after login

title is used to capitalize the first character of a word:

In [4]: &#39;i love python&#39;.title()
Out[4]: &#39;I Love Python&#39;
Copy after login

find is used to return the starting position index of the matching string:

In [5]: &#39;i love python&#39;.find(&#39;python&#39;)
Out[5]: 7
Copy after login

As an example of applying strings, determine whether str1 is composed of str2 is rotated.

String stringbook is rotated to obtain bookstring. Write a code to verify whether str1 is str2 obtained by rotation.

Convert to judgment: whether str1 is a substring of str2 str2.

下面函数原型中,注明了每个参数的类型、返回值的类型,增强代码的可读性和可维护性。

def is_rotation(s1: str, s2: str) -> bool:
   if s1 is None or s2 is None:
       return False
   if len(s1) != len(s2):
       return False

   def is_substring(s1: str, s2: str) -> bool:
       return s1 in s2
   return is_substring(s1, s2 + s2)
Copy after login

测试函数 is_rotation:

r = is_rotation(&#39;stringbook&#39;, &#39;bookstring&#39;)
print(r)  # True

r = is_rotation(&#39;greatman&#39;, &#39;maneatgr&#39;)
print(r)  # False
Copy after login

代码执行过程,动画演示:

55555

字符串的匹配操作除了使用 str 封装的方法外,Python 的 re 正则模块功能更加强大,写法更为简便,广泛适用于爬虫、数据分析等。

下面这个案例实现:密码安全检查,使用正则表达式非常容易实现。

密码安全要求:

  • 要求密码为 6 到 20 位;

  • 密码只包含英文字母和数字。

import re
pat = re.compile(r&#39;\w{6,20}&#39;) # 这是错误的,因为 \w 通配符匹配的是字母,数字和下划线,题目要求不能含有下划线
# 使用最稳的方法:\da-zA-Z 满足“密码只包含英文字母和数字”
# \d匹配数字 0-9
# a-z 匹配所有小写字符;A-Z 匹配所有大写字符
pat = re.compile(r&#39;[\da-zA-Z]{6,20}&#39;)
Copy after login

选用最保险的 fullmatch 方法,查看是否整个字符串都匹配。

以下测试例子都返回 None,原因都在解释里。

pat.fullmatch(&#39;qaz12&#39;) # 返回 None,长度小于 6
pat.fullmatch(&#39;qaz12wsxedcrfvtgb67890942234343434&#39;) # None 长度大于 22
pat.fullmatch(&#39;qaz_231&#39;) # None 含有下划线
Copy after login

下面这个字符串 n0passw0Rd 完全符合:

In [20]: pat.fullmatch(&#39;n0passw0Rd&#39;)
Out[20]: <re.Match object; span=(0, 10), match=&#39;n0passw0Rd&#39;>
Copy after login

自定义类型

Python 使用关键字 class 定制自己的类,self 表示类实例对象本身。

一个自定义类内包括属性、方法,其中有些方法是自带的。

类(对象):

class Dog(object):
   pass
Copy after login

以上定义一个 Dog 对象,它继承于根类 object,pass 表示没有自定义任何属性和方法。

下面创建一个 Dog 类型的实例:

wangwang = Dog()
Copy after login

Dog 类现在没有定义任何方法,但是刚才说了,它会有自带的方法,使用 dir() 查看这些自带方法:

In [26]: wangwang.__dir__()
Out[26]:
[&#39;__module__&#39;,
&#39;__dict__&#39;,
&#39;__weakref__&#39;,
&#39;__doc__&#39;,
&#39;__repr__&#39;,
&#39;__hash__&#39;,
&#39;__str__&#39;,
&#39;__getattribute__&#39;,
&#39;__setattr__&#39;,
&#39;__delattr__&#39;,
&#39;__lt__&#39;,
&#39;__le__&#39;,
&#39;__eq__&#39;,
&#39;__ne__&#39;,
&#39;__gt__&#39;,
&#39;__ge__&#39;,
&#39;__init__&#39;,
&#39;__new__&#39;,
&#39;__reduce_ex__&#39;,
&#39;__reduce__&#39;,
&#39;__subclasshook__&#39;,
&#39;__init_subclass__&#39;,
&#39;__format__&#39;,
&#39;__sizeof__&#39;,
&#39;__dir__&#39;,
&#39;__class__&#39;]
Copy after login

有些地方称以上方法为魔法方法,它们与创建类时自定义个性化行为有关。比如:

  • init 方法能定义一个带参数的类;

  • new 方法自定义实例化类的行为;

  • getattribute 方法自定义读取属性的行为;

  • setattr 自定义赋值与修改属性时的行为。

类的属性:

def __init__(self, name, dtype):
    self.name = name
    self.dtype = dtype
Copy after login

通过 init,定义 Dog 对象的两个属性:name、dtype。

类的实例:

wangwang = Dog(&#39;wangwang&#39;,&#39;cute_type&#39;)
Copy after login

wangwangDog 类的实例。

类的方法:

def shout(self):
   print(&#39;I\&#39;m %s, type: %s&#39; % (self.name, self.dtype))
Copy after login

注意:

  • 自定义方法的第一个参数必须是 self,它指向实例本身,如 Dog 类型的实例 dog;

  • 引用属性时,必须前面添加 self,比如 self.name 等。

总结以上代码:

In [40]: class Dog(object):
   ...:     def __init__(self,name,dtype):
   ...:         self.name=name
   ...:         self.dtype=dtype
   ...:     def shout(self):
   ...:         print('I\'m %s, type: %s' % (self.name, self.dtype))

In [41]: wangwang = Dog(&#39;wangwang&#39;,&#39;cute_type&#39;)

In [42]: wangwang.name
Out[42]: 'wangwang'

In [43]: wangwang.dtype
Out[43]: 'cute_type'

In [44]: wangwang.shout()
I'm wangwang, type: cute_type
Copy after login

看到创建的两个属性和一个方法都被暴露在外面,可被 wangwang 调用。这样的话,这些属性就会被任意修改:

In [49]: wangwang.name=&#39;wrong_name&#39;
   
In [50]: wangwang.name
Out[50]: &#39;wrong_name&#39;
Copy after login

如果想避免属性 name 被修改,可以将它变为私有变量。改动方法:属性前加 2 个 _ 后,变为私有属性。如:

In [51]: class Dog(object):
   ...:     def __init__(self,name,dtype):
   ...:         self.__name=name
   ...:         self.__dtype=dtype
   ...:     def shout(self):
   ...:         print(&#39;I\&#39;m %s, type: %s&#39; % (self.name, self.dtype))
Copy after login

同理,方法前加 2 个 _ 后,方法变为“私有方法”,只能在 Dog 类内被共享使用。

但是这样改动后,属性 name 不能被访问了,也就无法得知 wangwang 的名字叫啥。不过,这个问题有一种简单的解决方法,直接新定义一个方法就行:

def get_name(self):
   return self.__name
Copy after login

综合代码:

In [52]: class Dog(object):
   ...:     def __init__(self,name,dtype):
   ...:         self.__name=name
   ...:         self.__dtype=dtype
   ...:     def shout(self):
   ...:         print('I\'m %s, type: %s' % (self.name, self.dtype))
   ...:     def get_name(self):
   ...:         return self.__name
   ...:

In [53]: wangwang = Dog(&#39;wangwang&#39;,&#39;cute_type&#39;)

In [54]: wangwang.get_name()
Out[54]: 'wangwang'
Copy after login

但是,通过此机制,改变属性的可读性或可写性,怎么看都不太优雅!因为无形中增加一些冗余的方法,如 get_name。

下面,通过另一个例子,解释如何更优雅地改变某个属性为只读或只写。

自定义一个最精简的 Book 类,它继承于系统的根类 object:

class Book(object):
   def __init__(self,name,sale):
       self.__name = name
       self.__sale = sale
Copy after login

使用 Python 自带的 property 类,就会优雅地将 name 变为只读的。

   @property
   def name(self):
       return self.__name
Copy after login

使用 @property 装饰后 name 变为属性,意味着 .name 就会返回这本书的名字,而不是通过 .name() 这种函数调用的方法。这样变为真正的属性后,可读性更好。

In [101]: class Book(object):
    ...:     def __init__(self,name,sale):
    ...:         self.__name = name
    ...:         self.__sale = sale
    ...:     @property
    ...:     def name(self):
    ...:         return self.__name

In [102]: a_book = Book(&#39;magic_book&#39;,100000)

In [103]: a_book.name
Out[103]: &#39;magic_book&#39;
Copy after login

property 是 Python 自带的类,前三个参数都是函数类型。更加详细的讨论放在后面讨论装饰器时再展开。

In [104]: help(property)
Help on class property in module builtins:

class property(object)
|  property(fget=None, fset=None, fdel=None, doc=None)
Copy after login

如果使 name 既可读又可写,就再增加一个装饰器 @name.setter。

In [105]: class Book(object):
    ...:     def __init__(self,name,sale):
    ...:         self.__name = name
    ...:         self.__sale = sale
    ...:     @property
    ...:     def name(self):
    ...:         return self.__name
    ...:     @name.setter
    ...:     def name(self,new_name):
    ...:         self.__name = new_name

In [106]: a_book = Book(&#39;magic_book&#39;,100000)

In [107]: a_book.name = &#39;magic_book_2.0&#39;

In [108]: a_book.name
Out[108]: &#39;magic_book_2.0&#39;
Copy after login

注意这种装饰器写法:name.setter,name 已经被包装为 property 实例,调用实例上的 setter 函数再包装 name 后就会可写。对于 Python 入门者,可以暂时不用太纠结这部分理论,使用 Python 一段时间后,再回过头来自然就会理解。

The above is the detailed content of Analyze examples of four main data types in Python. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

GitLab's plug-in development guide on Debian GitLab's plug-in development guide on Debian Apr 13, 2025 am 08:24 AM

Developing a GitLab plugin on Debian requires some specific steps and knowledge. Here is a basic guide to help you get started with this process. Installing GitLab First, you need to install GitLab on your Debian system. You can refer to the official installation manual of GitLab. Get API access token Before performing API integration, you need to get GitLab's API access token first. Open the GitLab dashboard, find the "AccessTokens" option in the user settings, and generate a new access token. Will be generated

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

What service is apache What service is apache Apr 13, 2025 pm 12:06 PM

Apache is the hero behind the Internet. It is not only a web server, but also a powerful platform that supports huge traffic and provides dynamic content. It provides extremely high flexibility through a modular design, allowing for the expansion of various functions as needed. However, modularity also presents configuration and performance challenges that require careful management. Apache is suitable for server scenarios that require highly customizable and meet complex needs.

See all articles