Python主要数据类型包括list(列表)、tuple(元组)、dict(字典)和set(集合)等对象,下面逐一介绍这些Python数据类型。

    list(列表)是Python内置的一种数据类型,作为一个有序的数据集合,list的元素是可变的,可随意添加或删减list中的元素。在Python交互式命令中运行list相关代码:

>>> list_1 = ['one', 'two', 'three']
>>> list_1
['one', 'two', 'three']

    对象list_1就是一个list,我们可以使用索引来访问list中的每个元素,Python中的索引是从0开始计算的:

>>> list_1[0]
'one'
>>> list_1[2]
 'three'

    也可以倒着访问list中的每个对象:

>>> list_1[-1]
 'three'

    在往list中添加对象时可以使用append方法:

>>> list_1.append('four')
>>> list_1
['one', 'two', 'three','four']

    想要删除list中的某个对象可以使用pop方法:

>>> list_1.pop(1)
 'two'
>>> list_1
['one', 'three']

    list 也可以作为单个元素包含在另一个list中:

>>> player=['Curry','Leonard']
>>> NBAplayer=['Westbrook', 'Harden',palyer,'Durant']

    再来看Python的另一种重要的数据类型:tuple(元组)。tuple和list十分类似,不同的是tuple是以括号()形式存在的,且tuple一旦初始化后就不能像list一样可以随意修改了。

>>> tuple_1 = ('one', 'two', 'three')
>>> tuple_1
('one', 'two', 'three')

    tuple具有和list一样的对象元素访问功能,这里不再赘述。需要注意的是,因为tuple元素是不可变对象,相应的也就没有和list一样的append、pop等修改元素的方法。

    最后看Python中比较特殊的一种数据类型:dict(字典)。字典,顾名思义,肯定是具有强大的数据查询功能了。dict在其他程序语言中叫做map,具有key-value(键-值)的存储功能,看下面的示例:

>>> dict_1={'one':1, 'two':2}
>>> dict_1['one']
1

    除了在创建dict时指定各元素的key-value之外,还可以通过key来单独指定值放入:

>>> dict_1 ['three'] = 3
>>> dict_1['three']
3

    dict查找或插入数据的速度极快,但也占用了大量的内存,这一点正好和list相反。另一种和dict类似的数据类型叫做set(集合),它是一组key的集合但没有保存value,这里就不做介绍了。

 

 

>>>> 

Python 编程基础

 

    今天我主要介绍if-else条件判断以及for和while的循环语句。条件判断和循环作为任一编程语言的基础课有必要在此重点强调说明。先看Python中的if-else条件判断语句:

score = 66
if score >= 60:
    print('The scores are qualified!')
else:
    print('The scores are unqualified!')

    我们也可以用elif做更细致的条件判断:

score = 66
if score >= 90:
    print('
Excellent!')
elif 80<=points<90:
    print('Fine!')
elif 60<=points<80:
    print('
Secondary!')
else:
    print('
Unqualified!')

    Py循环语句和其他语言原理一致,这里不再详细展开,就以常见的高斯求和使用for和while循环为例来展示Python的循环功能。

    for循环:

sum=0
for x in range(101):
    sum = sum + x
print(sum)
5050

    while循环:

sum=0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)
5050