Analyze examples of four main data types in 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
Use e
to create a floating point number represented in scientific notation:
1.05e3 # 1050.0
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 变量
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:
Use a pair of brackets ()
to create a tuple object:
tup = (1,3,5) # tuple 变量
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:
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,) # 必须保留逗号
Otherwise it will be considered the element itself:
In [14]: tup=(1) ...: print(type(tup)) <class 'int'>
Use a pair of curly braces {}
and use a colon :
to create a dict object:
dic = {'a':1, 'b':3, 'c':5} # dict变量
The dictionary is a hash table. The following diagram vividly expresses the "shape" of the dictionary.
Use only a pair of curly braces {}
to create a set object:
s = {1,3,5} # 集合变量
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
Code execution process, animation demonstration:
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
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('%d*%d=%d'%(j,i,j*i),end='\t') ...: print()
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]
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]: ' I love python\t\n '.strip() Out[1]: 'I love python'
replace is used to replace strings:
In [2]: 'i love python'.replace(' ','_') Out[2]: 'i_love_python'
join is used to merge strings:
In [3]: '_'.join(['book', 'store','count']) Out[3]: 'book_store_count'
title is used to capitalize the first character of a word:
In [4]: 'i love python'.title() Out[4]: 'I Love Python'
find is used to return the starting position index of the matching string:
In [5]: 'i love python'.find('python') Out[5]: 7
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)
测试函数 is_rotation:
r = is_rotation('stringbook', 'bookstring') print(r) # True r = is_rotation('greatman', 'maneatgr') print(r) # False
代码执行过程,动画演示:
55555
字符串的匹配操作除了使用 str 封装的方法外,Python 的 re 正则模块功能更加强大,写法更为简便,广泛适用于爬虫、数据分析等。
下面这个案例实现:密码安全检查,使用正则表达式非常容易实现。
密码安全要求:
要求密码为 6 到 20 位;
密码只包含英文字母和数字。
import re pat = re.compile(r'\w{6,20}') # 这是错误的,因为 \w 通配符匹配的是字母,数字和下划线,题目要求不能含有下划线 # 使用最稳的方法:\da-zA-Z 满足“密码只包含英文字母和数字” # \d匹配数字 0-9 # a-z 匹配所有小写字符;A-Z 匹配所有大写字符 pat = re.compile(r'[\da-zA-Z]{6,20}')
选用最保险的 fullmatch 方法,查看是否整个字符串都匹配。
以下测试例子都返回 None,原因都在解释里。
pat.fullmatch('qaz12') # 返回 None,长度小于 6 pat.fullmatch('qaz12wsxedcrfvtgb67890942234343434') # None 长度大于 22 pat.fullmatch('qaz_231') # None 含有下划线
下面这个字符串 n0passw0Rd
完全符合:
In [20]: pat.fullmatch('n0passw0Rd') Out[20]: <re.Match object; span=(0, 10), match='n0passw0Rd'>
自定义类型
Python 使用关键字 class 定制自己的类,self 表示类实例对象本身。
一个自定义类内包括属性、方法,其中有些方法是自带的。
类(对象):
class Dog(object): pass
以上定义一个 Dog 对象,它继承于根类 object,pass 表示没有自定义任何属性和方法。
下面创建一个 Dog 类型的实例:
wangwang = Dog()
Dog 类现在没有定义任何方法,但是刚才说了,它会有自带的方法,使用 dir() 查看这些自带方法:
In [26]: wangwang.__dir__() Out[26]: ['__module__', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
有些地方称以上方法为魔法方法,它们与创建类时自定义个性化行为有关。比如:
init 方法能定义一个带参数的类;
new 方法自定义实例化类的行为;
getattribute 方法自定义读取属性的行为;
setattr 自定义赋值与修改属性时的行为。
类的属性:
def __init__(self, name, dtype): self.name = name self.dtype = dtype
通过 init,定义 Dog 对象的两个属性:name、dtype。
类的实例:
wangwang = Dog('wangwang','cute_type')
wangwang
是 Dog
类的实例。
类的方法:
def shout(self): print('I\'m %s, type: %s' % (self.name, self.dtype))
注意:
自定义方法的第一个参数必须是 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('wangwang','cute_type') 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
看到创建的两个属性和一个方法都被暴露在外面,可被 wangwang 调用。这样的话,这些属性就会被任意修改:
In [49]: wangwang.name='wrong_name' In [50]: wangwang.name Out[50]: 'wrong_name'
如果想避免属性 name 被修改,可以将它变为私有变量。改动方法:属性前加 2 个 _
后,变为私有属性。如:
In [51]: 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))
同理,方法前加 2 个 _
后,方法变为“私有方法”,只能在 Dog 类内被共享使用。
但是这样改动后,属性 name 不能被访问了,也就无法得知 wangwang 的名字叫啥。不过,这个问题有一种简单的解决方法,直接新定义一个方法就行:
def get_name(self): return self.__name
综合代码:
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('wangwang','cute_type') In [54]: wangwang.get_name() Out[54]: 'wangwang'
但是,通过此机制,改变属性的可读性或可写性,怎么看都不太优雅!因为无形中增加一些冗余的方法,如 get_name。
下面,通过另一个例子,解释如何更优雅地改变某个属性为只读或只写。
自定义一个最精简的 Book 类,它继承于系统的根类 object:
class Book(object): def __init__(self,name,sale): self.__name = name self.__sale = sale
使用 Python 自带的 property 类,就会优雅地将 name 变为只读的。
@property def name(self): return self.__name
使用 @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('magic_book',100000) In [103]: a_book.name Out[103]: 'magic_book'
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)
如果使 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('magic_book',100000) In [107]: a_book.name = 'magic_book_2.0' In [108]: a_book.name Out[108]: 'magic_book_2.0'
注意这种装饰器写法: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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.

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

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

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

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.
