python基础2--数据结构(列表List、元组Tuple、字典Dict)

1、Print函数中文编码问题

print中的编码:# -*- coding: utf-8 -*-

注:此处的#代表的是配置信息

print中的换行符,与C语言相同,为"\n"

 

2、数据结构List(列表)

# -*- coding: utf-8 -*-

#创建List
number_list = [1, 3, 5, 7, 9]
string_list = ["abc", "bbc", "python"]
mixed_list = ['python', 'java', 3, 12]

#访问List中的值
second_num = number_list[1]
third_string = string_list[2]
fourth_mix = mixed_list[3]
print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix))

#更新List
print("number_list before: " + str(number_list))
number_list[1] = 30
print("number_list after: " + str(number_list))

#删除List元素
print("mixed_list before delete: " + str(mixed_list))
del mixed_list[2]
print("mixed_list after delete: " + str(mixed_list))

#Python脚本语言
print(len([1,2,3])) #长度
print([1,2,3] + [4,5,6]) #组合
print(['Hello'] * 4) #重复
print(3 in [1,2,3]) #某元素是否在列表中

#List的截取
abcd_list =['a', 'b', 'c', 'd']
print(abcd_list[1])
print(abcd_list[-2])
print(abcd_list[1:])
print(abcd_list[-2:])

 运行结果:

列表操作包含以下函数:
(1) cmp(list1, list2):比较两个列表的元素
(2) len(list):列表元素个数
(3) max(list):返回列表元素最大值
(4) min(list):返回列表元素最小值
(5) list(seq):将元组转换为列表
列表操作包含以下方法:
(1) list.append(obj):在列表末尾添加新的对象
(2) list.count(obj):统计某个元素在列表中出现的次数
(3) list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
(4) list.index(obj):从列表中找出某个值第一个匹配项的索引位置
(5) list.insert(index, obj):将对象插入列表
(6) list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
(7) list.remove(obj):移除列表中某个值的第一个匹配项
(8) list.reverse():反向列表中元素
(9) list.sort([func]):对原列表进行排序

 

3、数据结构Tuple(元组)

#创建只有一个元素的tuple,需要用逗号结尾消除歧义
a_tuple = (2,)

#tuple中的list
mixed_tuple = (1, 2, ['a', 'b'])
print("mixed_tuple: " + str(mixed_tuple))
mixed_tuple[2][0] = 'c'
mixed_tuple[2][1] = 'd'
print("mixed_tuple: " + str(mixed_tuple))

运行结果:

 

Tuple是不可变List。一旦创建了一个tuple就不能以任何方式改变它。

Tuple与List的相同之处

定义Tuple与定义List的方式相同, Tuple用, List用方括号。

Tuple的元素与List一样按定义的次序进行排序。Tuples的索引与List一样从 0 开始, 所以一个非空Tuple的第一个元素总是 t[0]。

负数索引与List一样从Tuple的尾部开始计数。

与List一样分片 (slice) 也可以使用。注意当分割一个 List 时, 会得到一个新的 List ;当分割一个Tuple时, 会得到一个新的Tuple。

Tuple不存在的方法

不能向Tuple增加元素。Tuple没有append或extend方法。

不能从Tuple删除元素。Tuple没有remove或pop方法。

可以使用in来查看一个元素是否存在于Tuple中。

用Tuple的好处

Tuple比List操作速度快。如果您定义了一个值的常量集,并且唯一要用它做的是不断地遍历它,请使用Tuple代替List。

如果对不需要修改的数据进行 “写保护”,可以使代码更安全。使用Tuple而不是List如同拥有一个隐含的assert语句,说明这一数据是常量。如果必须要改变这些值,则需要执行Tuple到List的转换。

Tuple与List的转换

Tuple可以转换成List,反之亦然。内置的Tuple函数接收一个List,并返回一个有着相同元素的 Tuple。而 List 函数接收一个Tuple返回一个List。从效果上看,Tuple冻结一个List,而 List解冻一个Tuple。

Tuple的其他应用

一次赋多值

>>> v = ('a', 'b', 'e')

>>> (x, y, z) = v

解释:v是一个三元素的Tuple, 并且 (x, y, z) 是一个三变量的Tuple。将一个Tuple赋值给另一个Tuple, 会按顺序将v 的每个值赋值给每个变量。

 

4、数据结构Dict(字典)

Dict为key-value键值对形式

# -*- coding: utf-8 -*-

#创建一个词典
phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789}
mixed_dict = {"Tom": 'boy', 11: 23.5}

#访问词典里的值
print("Tom's number is " + str(phone_book['Tom']))
print('Tom is a ' + mixed_dict['Tom'])


#修改词典
phone_book['Tom'] = 999
phone_book['Heath'] = 888
print("phone_book: " + str(phone_book))
phone_book.update({'Ling':159, 'Lili':247})
print("updated phone_book: " + str(phone_book))

#删除词典元素以及词典本身
del phone_book['Tom']
print("phone_book after deleting Tom: " + str(phone_book))

#清空词典
phone_book.clear()
print("after clear: " + str(phone_book))

#删除词典
del phone_book
# print("after del: " + str(phone_book))
#不可执行, del后, 字典不存在

#不允许同一个键出现两次
rep_test = {'Name': 'aa', 'age':5, 'Name': 'bb'}
print("rep_test: " + str(rep_test))
#可执行, 'Name'为 'bb'

#键必须不可变,所以可以用书,字符串或者元组充当,列表不行
#list_dict = {['Name']: 'John', 'Age':13}
#不可执行,list不能当作key,因为list可变
list_dict = {('Name'): 'John', 'Age':13}

字典内置以下函数

(1) cmp(dict1, dict2):比较两个字典元素。

(2) len(dict):计算字典元素个数,即键的总数。

(3) str(dict):输出字典可打印的字符串表示。

(4) type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

字典内置以下方法:

(1) radiansdict.clear():删除字典内所有元素

(2) radiansdict.copy():返回一个字典的浅复制

(3) radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

(4) radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值

(5) radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false

(6) radiansdict.items():以列表返回可遍历的(键, 值) 元组数组

(7) radiansdict.keys():以列表返回一个字典所有的键

(8) radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default

(9) radiansdict.update(dict2):把字典dict2的键/值对更新到dict里

(10) radiansdict.values():以列表返回字典中的所有值

posted @ 2019-02-23 16:39  platycoden  阅读(610)  评论(0编辑  收藏  举报