📜  Python变量类型

📅  最后修改于: 2020-12-23 05:11:20             🧑  作者: Mango


变量不过是用于存储值的保留内存位置。这意味着当您创建变量时,会在内存中保留一些空间。

解释器根据变量的数据类型分配内存,并确定可以在保留内存中存储的内容。因此,通过为变量分配不同的数据类型,可以在这些变量中存储整数,小数或字符。

给变量赋值

Python变量不需要显式声明即可保留内存空间。为变量分配值时,声明自动发生。等号(=)用于为变量分配值。

=运算符左侧的操作数是变量的名称,=运算符右侧的操作数是存储在变量中的值。例如-

现场演示

#!/usr/bin/python

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print counter
print miles
print name

在这里,100、1000.0和“ John”分别是分配给counterMilesname变量的值。这产生以下结果-

100
1000.0
John

多重分配

Python允许您同时为多个变量分配一个值。例如-

a = b = c = 1

在这里,将创建一个整数对象,其值为1,并且所有三个变量都分配给相同的存储位置。您还可以将多个对象分配给多个变量。例如-

a,b,c = 1,2,"john"

在此,分别将两个具有值1和2的整数对象分配给变量a和b,并将一个具有值“ john”的字符串对象分配给变量c。

标准数据类型

存储在存储器中的数据可以有多种类型。例如,一个人的年龄存储为一个数字值,而他或她的地址存储为一个字母数字字符。 Python具有各种标准数据类型,这些数据类型用于定义可能的操作以及每种操作的存储方法。

Python具有五种标准数据类型-

  • 号码
  • 清单
  • 元组
  • 字典

Python数字

数字数据类型存储数值。数字对象是在您为其分配值时创建的。例如-

var1 = 1
var2 = 10

您也可以使用del语句删除对数字对象的引用。 del语句的语法是-

del var1[,var2[,var3[....,varN]]]]

您可以使用del语句删除单个对象或多个对象。例如-

del var
del var_a, var_b

Python支持四种不同的数字类型-

  • int(有符号整数)
  • long(长整数,也可以用八进制和十六进制表示)
  • 浮点数(浮点实数值)
  • 复数(复数)

例子

这是一些数字的例子-

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Python允许您使用带长号的小写字母l,但建议您仅使用大写字母L以避免与数字1混淆Python显示带大写字母L的长整数。

  • 复数由有序对的实数浮点数组成,用x + yj表示,其中x和y是实数,j是虚数单位。

Python字符串

Python中的字符串被标识为用引号引起来的一组连续字符。 Python允许使用单引号或双引号。可以使用切片运算符([]和[:])来获取字符串的子集,其中索引的起始位置为字符串的开头0,字符串的索引为-1。

加号(+)是字符串连接运算符,星号(*)是重复运算符。例如-

现场演示

#!/usr/bin/python

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string

这将产生以下结果-

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python列表

列表是Python复合数据类型中功能最多的。列表包含用逗号分隔并括在方括号([])中的项目。在某种程度上,列表类似于C中的数组。它们之间的区别是,属于列表的所有项目都可以具有不同的数据类型。

可以使用切片运算符([]和[:])访问列表中存储的值,其中的索引从列表开头的0开始,一直到-1结束。加号(+)是列表串联运算符,星号(*)是重复运算符。例如-

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

这产生以下结果-

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python元组

元组是另一种类似于列表的序列数据类型。一个元组由多个用逗号分隔的值组成。但是,与列表不同,元组被括在括号内。

列表和元组之间的主要区别是:列表放在方括号([])中,并且它们的元素和大小可以更改,而元组放在括号(())中并且不能更新。元组可以被视为只读列表。例如-

现场演示

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple               # Prints the complete tuple
print tuple[0]            # Prints first element of the tuple
print tuple[1:3]          # Prints elements of the tuple starting from 2nd till 3rd 
print tuple[2:]           # Prints elements of the tuple starting from 3rd element
print tinytuple * 2       # Prints the contents of the tuple twice
print tuple + tinytuple   # Prints concatenated tuples

这产生以下结果-

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

以下代码对元组无效,因为我们试图更新元组,这是不允许的。列表可能有类似情况-

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list

Python字典

Python的字典是一种哈希表类型。它们的工作方式类似于在Perl中找到的关联数组或哈希,并且由键值对组成。字典键几乎可以是任何Python类型,但通常是数字或字符串。另一方面,值可以是任意Python对象。

字典用花括号({})括起来,可以使用方括号([])分配和访问值。例如-

现场演示

#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one']       # Prints value for 'one' key
print dict[2]           # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values

这产生以下结果-

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

字典没有元素间顺序的概念。说元素“乱序”是不正确的。他们只是无序的。

数据类型转换

有时,您可能需要在内置类型之间执行转换。要在类型之间进行转换,只需将类型名称用作函数。

有几种内置函数可以执行从一种数据类型到另一种数据类型的转换。这些函数返回一个表示转换后值的新对象。

Sr.No. Function & Description
1

int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2

long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3

float(x)

Converts x to a floating-point number.

4

complex(real [,imag])

Creates a complex number.

5

str(x)

Converts object x to a string representation.

6

repr(x)

Converts object x to an expression string.

7

eval(str)

Evaluates a string and returns an object.

8

tuple(s)

Converts s to a tuple.

9

list(s)

Converts s to a list.

10

set(s)

Converts s to a set.

11

dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

12

frozenset(s)

Converts s to a frozen set.

13

chr(x)

Converts an integer to a character.

14

unichr(x)

Converts an integer to a Unicode character.

15

ord(x)

Converts a single character to its integer value.

16

hex(x)

Converts an integer to a hexadecimal string.

17

oct(x)

Converts an integer to an octal string.