奠定Python基础操作,超详细的列表、元组、集合与字典讲解

学编程什么最重要?当然是基础了!为奠定Python基础操作,跟大家讲一下Python中的容器。

Python容器包括列表、元组、集合与字典。

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

这些数据结构中都涉及到很多的方法,这里对比较常用的一些方法进行介绍,不用每个方法都记住,熟悉常用的即可。

首先,我们先来看列表。

一、列表的创建方式

<code># -*- coding: utf-8 -*-

# __author : Demon

# date : 1/16/18 8:19 PM

# 列表的创建

empty_list_01 = [] # 创建一个空的列表

empty_list_02 = list() # 创建一个空的列表

num_list = [1, 2, 3, 4, 5] # 创建一个数字列表

str_list = ['a', 'b', 'c'] # 创建一个字符串列表

mix_list = [1, 'a', 'abc'] # 一个列表中可包含元素类型不是固定的

nest_list = [num_list, str_list, mix_list] # 列表可以嵌套

print(num_list) # [1, 2, 3, 4, 5]

print(str_list) # ['a', 'b', 'c']


# 由打印结果可以看出列表的存储是有顺序的

# 即怎么存的就怎么取

print(num_list[0]) # 列表接受下标访问,类似于JAVA中的数组 1

print(num_list[1]) # 列表接受下标访问,类似于JAVA中的数组 2

print(num_list[2]) # 列表接受下标访问,类似于JAVA中的数组 3

print(num_list[3]) # 列表接受下标访问,类似于JAVA中的数组 4

print(num_list[4]) # 列表接受下标访问,类似于JAVA中的数组 5

# 一旦超出长度,就会抛出异常

# print(num_list[5]) # IndexError: list index out of range/<code>

二、列表中的常用操作

<code># -*- coding: utf-8 -*-

# __author : Demon

# date : 1/16/18 8:19 PM/<code>

1. 列表的循环方式【重要】

<code>num_list = [1, 2, 3, 4, 5] # 创建一个数字列表

for num in num_list:


print(num, end="") # 123456

print()/<code>

2. 求长度

<code>num_list = [1, 2, 3, 4, 5] # 创建一个数字列表

print(len(num_list)) # 5/<code>

3. 判断列表是否为空【重要】

<code>empty_list = list()

num_list = [1, 2, 3]

# 利用非0即True的原则【推荐方法】

if not empty_list: # 如果列表为空

print("The list is empty")

else:

print("The list is not empty")

# 利用长度

if not len(num_list):

print("The list is empty")

else:

print("The list is not empty")/<code>

4. 判断元素是否存在【重要】

<code>num_list = [1, 2, 3]

if 2 in num_list:

print("in")

else:

print("not in")

# 5\\. append(ele) 尾端添加元素

empty_list = [] # 创建一个空的列表

for s in "Hello":

empty_list.append(s)

print(empty_list) # ['H', 'e', 'l', 'l', 'o']/<code>

上述代码也是将字符串转换为列表的一种方式,只是代码比较复杂

6. 列表切片的用法,如字符串切片的用法类似【重要】

<code># 用法 list[start:end:step]

# start可省略,默认值为0

# end可省略,默认为最大长度

# step可省略,默认为1

# 范围是[start, end),即左闭右开

str_list = ['a', 'b', 'c'] # 创建一个字符串列表

# 获取整个list, ['a', 'b', 'c']

print(str_list[::])

print(str_list[0:])


print(str_list[:3])

print(str_list[:200]) # 长度超出时,不会报错

# 获取部分

print(str_list[0:2]) # ['a', 'b']

print(str_list[0:2:2]) # ['a']/<code>

7.sort排序【重要】

注意这个方法没有返回值,是在原列表上进行修改

<code>str_list = ["adfas", "dsdfw", "nklo"]

str_list.sort()

print(str_list) # ['adfas', 'dsdfw', 'nklo']/<code>

8.insert(pos, ele) 在指定位置插入元素

<code>str_list = ['a', 'b', 'c'] # 创建一个字符串列表

str_list.insert(2, "we") # ['a', 'b', 'we', 'c']

print(str_list)

# 如果位置超出长度,不会报错,会在尾部插入

str_list.insert(20, "we") # [['a', 'b', 'we', 'c', 'we']

print(str_list)/<code>

9.del(pos) 删除指定位置的元素

需要注意这个方法不是通过列表.调用的

可以类似理解为,它不是列表这个类中的方法

<code>str_list = ['a', 'b', 'c'] # 创建一个字符串列表

del str_list[0]

print(str_list) # ['b', 'c']

# del str_list[20] # IndexError: list assignment index out of range

# 10.extend(list)或+=合并

num_list = [1, 2]

str_list = ["a", "b"]

print(str_list + num_list) # ['a', 'b', 1, 2]/<code>

11.remove(ele) 删除指定值

<code>str_list = ['a', 'b', 'c'] # 创建一个字符串列表

str_list.remove("a")

print(str_list) # ['b', 'c']

# str_list.remove("d") # ValueError: list.remove(x): x not in list/<code>

12.pop(pos) 删除指定位置的元素

<code>str_list = ['a', 'b', 'c'] # 创建一个字符串列表

# str_val = str_list.pop(100) # IndexError: pop index out of range

str_val = str_list.pop(0)

print(str_val) # a

print(str_list) # ['b', 'c']/<code>

13.reverse() 反转,见练习

14.count(ele)方法查看某个元素出现的次数

<code>str_list = ['abc', 'b', 'c', "abc"]

print(str_list.count("abc")) # 2/<code>

三、列表的转换

其他形式转列表,采用list(otherType)的方法。

可以转列表的类型有:字符串,元组等,

如下代码所示:

<code>str_01 = "abc"

print(list(str_01)) # ['a', 'b', 'c']

tuple_01 = (1, 2, 3)

print(list(tuple_01)) # [1, 2, 3]/<code>

列表转其他形式,通常看其他形式是怎么支持转换。其中比较灵活的是列表转字符串,采用join的方法,如下代码所示:

<code>str_list = ["a", "b", "c"]

print(",".join(str_list)) # a,b,c

print("".join(str_list)) # abc/<code>

列表转字符串需要注意:

首先,join方法不是列表自带的方法,从调用来看,它是字符串里的方法;

其次,join方法,如果列表中的元素不是字符串,会报错,

如下代码所示:

<code>num_list = [1, 2, 3]

# print("".join(num_list))
# TypeError: sequence item 0: expected str instance, int found/<code>

四、常见的练习题

1. 列表的反转

方式一:调用列表的reverse()方法

<code>num_list = [1, 2, 3]

num_list.reverse()

print(num_list) # [3, 2, 1]/<code>

方式二:使用切片

<code>
num_list = [1, 2, 3]

for num in num_list[::-1]:

print(num)

# 如果需要[3, 2, 1]这样的格式

num_list = [1, 2, 3]

print("[", end="")

for num in num_list[:0:-1]:

print(num, end=", ")

if not num_list: # 如果列表为空

print("]")

else:

print("%d]" % num_list[0])

2.如何将列表拷贝到别一个列表中

nest_list = [1, 2, 3, ['a', 'b', 'c']]

new_nest_list = nest_list # 直接赋值拷贝

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c']]

new_nest_list.append("4")

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c'], '4']

print(nest_list) # [1, 2, 3, ['a', 'b', 'c'], '4']

# 直接赋值的拷贝会影响原来的列表,是一种浅拷贝

nest_list = [1, 2, 3, ['a', 'b', 'c']]

new_nest_list = nest_list[::] # 切片


print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c']]

new_nest_list.append("4")

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c'], '4']

print(nest_list) # [1, 2, 3, ['a', 'b', 'c']]

nest_list[-1].append("d")

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c', 'd'], '4']

print(nest_list) # [1, 2, 3, ['a', 'b', 'c', 'd']]

# 使用切片,改变最外层对原列表没有影响,而内层是有影响的。这也是一种浅拷贝

nest_list = [1, 2, 3, ['a', 'b', 'c']]

new_nest_list = nest_list.copy() # 使用copy方法

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c']]

new_nest_list.append("4")

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c'], '4']

print(nest_list) # [1, 2, 3, ['a', 'b', 'c']]

nest_list[-1].append("d")

print(new_nest_list) # [1, 2, 3, ['a', 'b', 'c', 'd'], '4']

print(nest_list) # [1, 2, 3, ['a', 'b', 'c', 'd']]/<code>

使用copy,改变最外层对原列表没有影响,而内层是有影响的。

这也是一种浅拷贝。

如果想要实现深拷贝,需要使用copy模块中的deepcopy方法,详见<python>一文/<python>

3.列表的排序

列表的简单排序通常使用list.sort()方法。

但是这个sort方法使用会相对比较灵活。

它的完整定义如下:

<code>sort(*, key=None, reverse=False)

key指定一个函数名,并且这个函数只能接受一个参数

reverse指定排序的方式

x = ['bc', 'essmm', 'mdsfm', 'ss' ]

x.sort(key=str.lower)

print(x) # ['bc', 'essmm', 'mdsfm', 'ss']

y = [3, 2, 8, 0, 1]

y.sort(reverse=True)

print(y) # [8, 3, 2, 1, 0]/<code>

可以发现,使用list.sort()方法进行排序,是调用的列表中自带的方法.

并且它是作用于原列表,并没有返回值。

如果我们想要得到一个新的排好序的列表,则需要使用到sorted()方法。

最后小编帮助大家整理了一套python教程,下面展示了部分,希望也能帮助对编程感兴趣,想做数据分析,人工智能、爬虫或者希望从事编程开发的小伙伴,毕竟python工资也还可以,如果能帮到你请点赞、点赞、点赞。

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

奠定Python基础操作,超详细的列表、元组、集合与字典讲解

如果你喜欢python,并觉得这篇文章对你有益的话,麻烦多多点赞关注支持!!!!


分享到:


相關文章: