Python Data Types
In this tutorial, you will learn about different data types you can use in Python.
Table of Contents
- Data Types in Python
- Python Numbers
- Python List
- Python Tuple
- Python Strings
- Python Set
- Python Dictionary
- Conversion between data types
表格内容
- Python数据类型
- 数字
- 列表
- 元组
- 字符串
- 集合
- 字典
- 数据类型交换
Data types in Python
Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are listed below.
Python的数据类型
任何值在Python中都有一个数据类型。因为在Python程序中任何事物都是一个对象,数据类型实际上是一个类类,变量是这些类的实例(对象).
在Python中有各种数据类型。在下面列出一些重要的类型。
Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int
, float
and complex
class in Python.
We can use the type()
function to know which class a variable or a value belongs to and the isinstance()
function to check if an object belongs to a particular class.
1
2
3
4
5
6
7
8
9a = 5 print(a, "is of type", type(a)) a = 2.0 print(a, "is of type", type(a)) a = 1+2j print(a, "is complex number?", isinstance(1+2j,complex))
数字
整数,浮点数和复数属于Python数字类别。在Python中它们被定义为int、float、complex类。
我可以使用type()函数去了解哪一个变量或值属于哪一类的,用ininstance()函数去检查一个对象是否属于某个特殊的类。
1
2
3
4
5
6
7
8
9>>> a = 5 >>> print(a,"is of type",type(a)) 5 is of type <class 'int'> >>> a = 2.0 >>> print(a,"is of type",type(a)) 2.0 is of type <class 'float'> >>> a = 1+2j >>> print(a,"is complex number?",isinstance(1+2j,complex)) (1+2j) is complex number? True
Integers can be of any length, it is only limited by the memory available.
A floating point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1
is integer, 1.0
is floating point number.
Complex numbers are written in the form, x + yj
, where x is the real part and y is the imaginary part. Here are some examples.
1
2
3
4
5
6
7
8
9>>> a = 1234567890123456789 >>> a 1234567890123456789 >>> b = 0.1234567890123456789 >>> b 0.12345678901234568 >>> c = 1+2j >>> c (1+2j)
整数不限定任何长度,它仅仅限制可用内存。
一个浮点数是精确到小数点15位。整数和浮点数数被小数点分割开的。1是整数,1.0是浮点数。
复数被写的形式是:x+yj,x是实部,y是虚部。这里有些例子。
Notice that the float
variable b got truncated.
注意:这里的浮点数变量被分隔了。
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
列表
列表是一个有序的项。在Python中它是被使用的最多之一,它是非常灵活的。在列表中所有的项不一定需要是同一个类型。
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].
1>>> a = [1, 2.2, 'python']
列表是相当直截了当的。每项之间用逗号分开,用中括号[]包围起来。
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python.
1
2
3
4
5
6
7
8
9
10a = [5,10,15,20,25,30,35,40] # a[2] = 15 print("a[2] = ", a[2]) # a[0:3] = [5, 10, 15] print("a[0:3] = ", a[0:3]) # a[5:] = [30, 35, 40] print("a[5:] = ", a[5:])
我们可以使用切片操作从列表中提取一项或一个范围的项。在Python中索引是从0开始的。
1
2
3
4
5
6
7>>> a = [5,10,15,20,25,30,35,40] >>> print("a[a] = ",a[2]) a[a] = 15 >>> print("a[0:3] = ",a[0:3]) a[0:3] = [5, 10, 15] >>> print("a[5:] = ",a[5:]) a[5:] = [30, 35, 40]
Lists are mutable, meaning, value of elements of a list can be altered.
1
2
3
4>>> a = [1,2,3] >>> a[2]=4 >>> a [1, 2, 4]
列表的可变的,意思是,列表中元素中的值是可以改变的。
Python Tuple
Tuple is an ordered sequence of items same as list.The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
1>>> t = (5,'program', 1+3j)
元组
元组和列表一样是有序的项。唯一的不同点是元组是不可变的。元组一旦创建就不能更改。
We can use the slicing operator [] to extract items but we cannot change its value.
- 复制代码1
2
3
4
5
6
7
8
9
10
11t = (5,'program', 1+3j) # t[1] = 'program' print("t[1] = ", t[1]) # t[0:3] = (5, 'program', (1+3j)) print("t[0:3] = ", t[0:3]) # Generates error # Tuples are immutable t[0] = 10
我们可以用切片操作符[]去提前每一项,但是我们不能改变它的值。
1
2
3
4
5
6
7
8
9
10>>> t = (5,'program',1+3j) >>> print("t[1] = ",t[1]) t[1] = program >>> print("t[0:3] = ",t[0:3]) t[0:3] = (5, 'program', (1+3j)) >>> t[0] = 10 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, '''
or """
.
1
2>>> s = "This is a string" >>> s = '''a multiline
字符串
字符串是Unicode字符的序列。我们可以使用单引号或双引号去代表字符串。多行字符串可以用三重引号,例如:'''或"""
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
1
2
3
4
5
6
7
8
9
10
11s = 'Hello world!' # s[4] = 'o' print("s[4] = ", s[4]) # s[6:11] = 'world' print("s[6:11] = ", s[6:11]) # Generates error # Strings are immutable in Python s[5] ='d'
像列表和元组一样,字符串可以使用切片操作符[]。字符串是不可变的。
1
2
3
4
5
6
7
8
9
10>>> s = 'Hello world!' >>> print("s[4] = ",s[4]) s[4] = o >>> print("s[6:11] = ",s[6:11]) s[6:11] = world >>> s[5] = 'd' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.
1
2
3
4
5
6
7
8a = {5,2,3,1,4} # printing set variable print("a = ", a) # data type of variable a print(type(a))
集合
Set是唯一项目无序的集合。定义一个集合是值被逗号分开,用大括号{}包围起来。在集合中的每一项可以是无序的。
1
2
3
4
5>>> a = {5,2,3,1,4} >>> print("a = ", a) a = {1, 2, 3, 4, 5} >>> print(type(a)) <class 'set'>
We can perform set operations like union, intersection on two sets. Set have unique values. They eliminate duplicates.
1
2
3>>> a = {1,2,2,3,3,3} >>> a {1, 2, 3}
我们可以在2个集合执行集合运输像交集,并集。集合有单独唯一值。它们可以消除重复值。
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not work.
1
2
3
4
5
6>>> a = {1,2,3} >>> a[1] Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> TypeError: 'set' object does not support indexing
因为,集合是无序集合,索引是无意义的。因此切片操作符[]是不能用的。
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value
. Key and value can be of any type.
1
2
3>>> d = {1:'value','key':2} >>> type(d) <class 'dict'>
字典
字典是一个键值对的无序集合。
当我们有一个大量的数据时,一般使用它。字典是为了检索数据作优化。我们必须了解这个健是为了优惠这个值。
在python,字典的定义的格式是每一项有一对key:value并用大括号{}包围起来。键和值可以是任何类型。
We use key to retrieve the respective value. But not the other way around.
1
2
3
4
5
6
7
8
9d = {1:'value','key':2} print(type(d)) print("d[1] = ", d[1]); print("d['key'] = ", d['key']); # Generates error print("d[2] = ", d[2]);
我们使用键去优惠各自的值。但是(键值)不能相反。
1
2
3
4
5
6
7
8
9
10
11
12>>> d = {1:'value','key':2} >>> print(type(d)) <class 'dict'> >>> print("d[1] = ",d[1]) d[1] = value >>> print("d['key'] = ",d['key']) d['key'] = 2 >>> print("d[2] = ",d[2]) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 2
Conversion between data types
We can convert between different data types by using different type conversion functions like int(), float(), str() etc.
1
2>>> float(5) 5.0
数据交换
我要转换不同的数据类型就可使用不同的转换函数,像int(),float(),str()等。
Conversion from float to int will truncate the value (make it closer to zero).
1
2
3
4>>> int(10.6) 10 >>> int(-10.6) -10
从小数转换为整数将会被截断(使它接近于0)
Conversion to and from string must contain compatible values.
1
2
3
4
5
6
7
8
9>>> float('2.5') 2.5 >>> str(25) '25' >>> int('1p') Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> ValueError: invalid literal for int() with base 10: '1p'
从字符串间的转换必须包含兼容的值。
We can even convert one sequence to another.
1
2
3
4
5
6>>> set([1,2,3]) {1, 2, 3} >>> tuple({5,6,7}) (5, 6, 7) >>> list('hello') ['h', 'e', 'l', 'l', 'o']
我们甚至可以从一个序列转换成另外一个。
To convert to dictionary, each element must be a pair
1
2
3
4>>> dict([[1,2],[3,4]]) {1: 2, 3: 4} >>> dict([(3,26),(4,44)]) {3: 26, 4: 44}
转换字典,每个元素必须是一对。
Check out these examples to learn more:
-
Python Program to Add Two Numbers
-
Python Program to Find the Square Root
-
Python Program to Calculate the Area of a Triangle
- PREVIOUS
Python Variables - NEXT
PYTHON TYPE CONVERSION
最后
以上就是高挑外套最近收集整理的关于python基础入门----数据类型Python Data Types的全部内容,更多相关python基础入门----数据类型Python内容请搜索靠谱客的其他文章。
发表评论 取消回复