search
HomeBackend DevelopmentPython Tutorial浅谈Python中的数据类型

数据类型:

float — 浮点数可以精确到小数点后面15位
int — 整型可以无限大
bool — 非零为true,零为false
list — 列表

Float/Int:

运算符:

/ — 浮点运算除
 // — 当结果为正数时,取整; 11//5 =2; 11//4 = 2
当结果为负数时,向下取整;-11//5=-3; -11//4=-3

当分子分母都是float,结果为float型

** —  计算幂; 11**2 =121
% — 取余

其他数学运算

1.分数:

import fractions;
fractions.Fraction(1,3) — 1/3
import math;
—math.sin()
—math.cos()
—math.tan()
—math.asin()

math.pi —3.1415926…
math.sin(math.pi/2) — 1.0
math.tan(math.pi/4) — 0.9999999999…
math.sin(); math

List:

创建: a_list = [‘a', ‘b', ‘mpilgrim', ‘z', ‘example']

a_list[-1] — ‘example'
a_list[0] — ‘a'
a_list[1:3] — [‘b', ‘mpilgrim', ‘z']
a_list[:3] — [‘a', ‘b', ‘mpilgrim' ]
a_list[3:] — [‘z', ‘example']
a_list[:]/a_list — [‘a', ‘b', ‘mpilgrim', ‘z', ‘example']

*注:a_list[:] 与a_list 返回的是不同的list,但它们拥有相同的元素

a_list[x:y]— 获取list切片,x指定第一个切片索引开始位置,y指定截止但不包含的切片索引位置。

向list添加元素:

a_list = [‘a']
a_list = a_list + [2.0, 3] — [‘a', 2.0, 3]
a_list.append(True) — [‘a', 2.0, 3, True]
a_list.extend([‘four','Ω']) — [‘a', 2.0, 3, True,'four','Ω']
a_list.insert(0,'Ω') — [‘Ω','a', 2.0, 3, True,'four','Ω']

list其他功能:

a_list = [‘a', ‘b', ‘new', ‘mpilgrim', ‘new']
a_list.count(‘new') — 2
a_list.count(‘mpilgrim') — 1
‘new' in a_list — True
a_list.index(‘new') — 2
a_list.index(‘mpilgrim') — 3
a_list.index(‘c') — through a exception because ‘c' is not in a_list.
del a_list[1] — [‘a', ‘new', ‘mpilgrim', ‘new']
a_list.remove(‘new') — [‘a', mpilgrim', ‘new']

注:remove只删除第一个'new'

a_list.pop() — 'new'/[‘a', mpilgrim' ](删除并返回最后一个元素)
a_list.pop(0) — ‘a' / [‘mpilgrim'] (删除并返回第0个元素)

空列表为假,其他列表为真。

元组(元素是不可变的列表):

定义:与列表的定义相同,除了整个元素的集合用圆括号而,不是方括号闭合

a_tuple = (“a”, “b”, “mpilgrim”, “z”, “example”)
a_tuple = (‘a', ‘b', ‘mpilgrim', ‘z', ‘example')

tuple 只能索引,不能修改。

元组相对于列表的优势:

1.速度快
2.“写保护”,更安全
3.一些元组可以当作字典键??

内置的tuple()函数接受一个列表参数并将列表转化成元组

同理,list()函数将元组转换成列表

同时赋多个值:

v = (‘a',2, True)
(x,y,z) = v — x=‘a', y=2, z=True

range() — 内置函数,进行连续变量赋值

(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) = range(7)

Monday — 0
    Thursday — 3
    Sunday — 6
        range() — 内置函数range()构建了一个整数序列,range()函数返回一个迭代器。

集合(里面的值是无序的):

    创建集合:用逗号分隔每个值,用大括号{}将所有值包括起来。
    a_set = {1}
    type(a_set) —
    以列表为基础创建集合:
    a_list = [‘a', ‘b', ‘mpilgrim', True, False, 42]
    a_set = set(a_list)
    a_set — {‘a', ‘b', ‘mpilgrim', True, False, 42}
    a_set = set() — 得到一个空的set
    a_dic = {} — 得到一个空的dic    

    修改集合:

    a_set = {1,2}
    a_set.add(4) — {1,2,4}
    len(a_set) — 3
    a_set.add(1) — {1,2,4}
    a_set.update({2,4,6}) — {1,2,4,6}
    a_set.update({3,6,9}, {1,2,3,5,8,13}) — {1,2,3,4,5,6,8,9,13}
    a_set.update([15,16]) — {1,2,3,4,5,6,8,9,13,15,16}
    a_set.discard(16) — {1,2,3,4,5,6,8,9,13,15}
    a_set.discard(16) — {1,2,3,4,5,6,8,9,13,15}
    a_set.remove(15) —{1,2,3,4,5,6,8,9,13}
    a_set.remove(15) — through a exception
    a_set.pop() — return 1 / {2,3,4,5,6,8,9,13}
    注:a_set.pop()随机删掉集合中的某个值并返回该值。
    a_set.clear() — set()
    a_set.pop() — through exception.  

    集合的其他运算:

    a_set = {2,3,4,5,6,8,9,13}
    30 in a_set — False
    4 in a_set — True
    b_set  = {3,4,10,12}
    a_set.union(b_set) — 两个集合的并
    a_set.intersetion(b_set) — 两个集合的交集
    a_set.difference(b_set) — a_set中有但是b_set中没有的元素
    a_set.symmetric_difference(b_set) — 返回所有只在一个集合中出现的元素
    a_set.issubset(b_set) — 判断a_set是否是b_set的子集
    b_set.issuperset(a_set) — 判断b_set是否是a_set的超集

    在布尔类型上下文环境中,空集合为假,任何包含一个以上元素的集合为真。

字典(键值对的无序集合):

    创建字典:

    a_dic = {‘server':'db.diveintopython3.org',
    ‘databas':'mysql'}
    a_dic[‘server'] — ‘db.diveintopython3.org'
    a_dic[‘database'] — ‘mysql' 

   修改字典:

    a_dic[‘user'] = ‘mark'  — {'user': 'mark', 'server': 'db.diveintopython3.org',     'database':     ‘blog'}
    a_dic[‘database'] = ‘blog' —  {'user': 'mark', 'server': 'db.diveintopython3.org',     'database': ‘blog'}
    a_dic[‘user'] = ‘bob' — {'user': 'bob', 'server': 'db.diveintopython3.org',     'database':     ‘blog'}
    a_dic[‘User'] = ‘mark' — {'user': 'bob', ‘Uuser': 'mark', 'server':     'db.diveintopython3.org', 'database': ‘blog'}

    注:1.在字典中不允许有重复的键。对现有键赋值将会覆盖原有值;
    2.随时可以添加新的键值对;
    3.字典键区分大小写。

    混合值字典:

    suffixes = { 1000:[‘KB', ‘MB', ‘GB', ‘TB', ‘PB', ‘EB', ‘ZB', ‘YB'],
        1024: [‘KiB', ‘MiB', ‘GiB', ‘TiB', ‘PiB' , ‘EiB', ‘ZiB', ‘YiB']}

    len(suffixes) — 2
    1000 in suffixes — True
    suffixes[1024] — [‘KiB', ‘MiB', ‘GiB', ‘TiB', ‘PiB' , ‘EiB', ‘ZiB', ‘YiB']
    suffixes[1000][3] — ‘TB'
   
    空字典为假, 所有其他字典为真

以上所述就是本文的全部内容了,希望大家能够喜欢。

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
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)