热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开发笔记:Python基础之数据类型和运算——列表

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python基础之数据类型和运算——列表相关的知识,希望对你有一定的参考价值。

篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python基础之数据类型和运算—— 列表相关的知识,希望对你有一定的参考价值。



列表

Python 有几个 复合数据类型,用于表示其它的值。最通用的是 list (列表) ,它可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型:


>>> squares = [1, 4, 9, 16, 25]
>>> squares
[
1, 4, 9, 16, 25]

 

索引:


names = [Alex,"Tenglan",Eric]
>>> names[0]
Alex
>>> names[2]
Eric
>>> names[-1]
Eric
>>> names[-2] #还可以倒着取
Tenglan

切片:


print(name_list[1:4])#取下标1至下标4之间的值,包括1,不包括4

print(name_list[1:-1])#取下标1至下标-1的值,不包括-1(-1为最右边的值)
print(name_list[1:])#从1开始取直到最后一个,不能写-1,只能这么写
print(name_list[1:len(name_list)])#同上
print(name_list[0:3])#从头开始取,取3个值
print(name_list[:3])#如果是从头开始取,0可以忽略,跟上句效果一样
print(name_list[0::2])#后面的2表示每隔一个元素,取一个
print(name_list[::2])#效果同上
print(name_list[-3:-1])#从右边数第3个到最后一个,不包括最后第一个
print(name_list[-3:])#从右边数第3个到最后一个

 

所有的切片操作都会返回一个包含请求的元素的新列表。这意味着下面的切片操作返回列表一个新的(浅)拷贝副本:


print(name_list[:])

修改:


>>> names
[
Alex, Tenglan, 强行从Eric前面插入, Eric, Rain, 从eric后面插入试试新姿势, Tom, Amy, 我是新来的]
>>> names[2] = "该换人了"
>>> names
[
Alex, Tenglan, 该换人了, Eric, Rain, 从eric后面插入试试新姿势, Tom, Amy, 我是新来的]

也可以对切片赋值,此操作可以改变列表的尺寸,或清空它:


>>> letters = [a, b, c, d, e, f, g]
>>> letters
[
a, b, c, d, e, f, g]
>>> # replace some values
>>> letters[2:5] = [C, D, E]
>>> letters
[
a, b, C, D, E, f, g]
>>> # now remove them
>>> letters[2:5] = []
>>> letters
[
a, b, f, g]
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

追加:


>>> names
[
Alex, Tenglan, Eric, Rain, Tom, Amy]
>>> names.append("我是新来的")
>>> names
[
Alex, Tenglan, Eric, Rain, Tom, Amy, 我是新来的]

扩展:


>>> names
[
Alex, Tenglan, Rain, Tom, Amy]
>>> b = [1,2,3]
>>> names.extend(b)
>>> names
[
Alex, Tenglan, Rain, Tom, Amy, 1, 2, 3]

列表也支持连接这样的操作:


>>> squares + [36, 49, 64, 81, 100]
[
1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

插入:


>>> names
[
Alex, Tenglan, Eric, Rain, Tom, Amy, 我是新来的]
>>> names.insert(2,"强行从Eric前面插入")
>>> names
[
Alex, Tenglan, 强行从Eric前面插入, Eric, Rain, Tom, Amy, 我是新来的]
>>> names.insert(5,"从eric后面插入试试新姿势")
>>> names
[
Alex, Tenglan, 强行从Eric前面插入, Eric, Rain, 从eric后面插入试试新姿势, Tom, Amy, 我是新来的]

删除:


>>> del names[2]
>>> names
[
Alex, Tenglan, Eric, Rain, 从eric后面插入试试新姿势, Tom, Amy, 我是新来的]
>>> del names[4]
>>> names
[
Alex, Tenglan, Eric, Rain, Tom, Amy, 我是新来的]
>>>
>>> names.remove("Eric") #删除指定元素,只能删一个
>>> names
[
Alex, Tenglan, Rain, Tom, Amy, 我是新来的]
>>> names.pop() #删除列表最后一个值
我是新来的
>>> names
[
Alex, Tenglan, Rain, Tom, Amy]

拷贝:


>>> names
[
Alex, Tenglan, Rain, Tom, Amy, 1, 2, 3]
>>> name_copy = names.copy()
>>> name_copy
[
Alex, Tenglan, Rain, Tom, Amy, 1, 2, 3]

此处的copy只能浅拷贝,即只能拷贝一层,例如:


>>> text = [a,b,c,d,[A,B,C],e,f]>>> text_copy = text.copy()
>>> text_copy
[
a, b, c, d, [A, B, C], e, f]
>>> text[4][1] = ZZZ
>>> text
[
a, b, c, d, [A, ZZZ, C], e, f]
>>> text_copy #并没有修改text_copy的内容,但是却被更改。证明这个copy 是浅拷贝
[
a, b, c, d, [A, ZZZ, C], e, f]

 在列表嵌套列表的存储中,实际存的是子列表的指针,浅拷贝拷贝的也是相应子列表指针,所以更改子列表元素原列表和复制列表都会改变。


>>> text_copy[4][0] = Yang
>>> text
[
a, b, c, d, [Yang, ZZZ, C], e, f]
>>> text_copy
[
a, b, c, d, [Yang, ZZZ, C], e, f]

 深层拷贝:


import copy #拷贝模块
text
= [a,b,c,d,[A,B,C],e,f]
print(" text=",text)
text_copy
= copy.deepcopy(text) #深层拷贝
print("text_copy=",text_copy)
text[
4][1] = "ZZZ"
print("Chang text: text=",text)
print("Chang text: text_copy=",text_copy)
text_copy[
4][0] = "Yang"
print("Chang text_copy: text=",text)
print("Chang text_copy: text_copy=",text_copy)
输出:
text
= [a, b, c, d, [A, B, C], e, f]
text_copy
= [a, b, c, d, [A, B, C], e, f]
Chang text: text
= [a, b, c, d, [A, ZZZ, C], e, f]
Chang text: text_copy
= [a, b, c, d, [A, B, C], e, f]
Chang text_copy: text
= [a, b, c, d, [A, ZZZ, C], e, f]
Chang text_copy: text_copy
= [a, b, c, d, [Yang, B, C], e, f]

深拷贝是完全拷贝,子列表也重新保存。

浅拷贝三种:


p1 = copy.copy(person)
p2
= person[:]
p3
= list(person)

 

 

统计:


>>> names
[
Alex, Tenglan, Amy, Tom, Amy, 1, 2, 3]
>>> names.count("Amy")
2

排序&翻转:


>>> names
[
Alex, Tenglan, Amy, Tom, Amy, 1, 2, 3]
>>> names.sort() #排序
Traceback (most recent call last):
File
"", line 1, in
TypeError: unorderable types: int()
#3.0里不同数据类型不能放在一起排序了,擦
>>> names[-3] = 1
>>> names[-2] = 2
>>> names[-1] = 3
>>> names
[
Alex, Amy, Amy, Tenglan, Tom, 1, 2, 3]
>>> names.sort()
>>> names
[
1, 2, 3, Alex, Amy, Amy, Tenglan, Tom]
>>> names.reverse() #反转
>>> names
[
Tom, Tenglan, Amy, Amy, Alex, 3, 2, 1]

获取下标:


>>> names
[
Tom, Tenglan, Amy, Amy, Alex, 3, 2, 1]
>>> names.index("Amy")
2 #只返回找到的第一个下标

 

 


技术分享图片技术分享图片

class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable‘s items
"""
def append(self, p_object): # real signature unknown; restored from __doc__
""" L.append(object) -- append object to end """
pass
def count(self, value): # real signature unknown; restored from __doc__
""" L.count(value) -> integer -- return number of occurrences of value """
return 0
def extend(self, iterable): # real signature unknown; restored from __doc__
""" L.extend(iterable) -- extend list by appending elements from the iterable """
pass
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
def insert(self, index, p_object): # real signature unknown; restored from __doc__
""" L.insert(index, object) -- insert object before index """
pass
def pop(self, index=None): # real signature unknown; restored from __doc__
"""
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass
def remove(self, value): # real signature unknown; restored from __doc__
"""
L.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass
def reverse(self): # real signature unknown; restored from __doc__
""" L.reverse() -- reverse *IN PLACE* """
pass
def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
"""
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
"""
pass
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x """
pass
def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass
def __delslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__delslice__(i, j) <==> del x[i:j]

Use of negative indices is not supported.
"""
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__(‘name‘) <==> x.name """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.
"""
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __iadd__(self, y): # real signature unknown; restored from __doc__
""" x.__iadd__(y) <==> x+=y """
pass
def __imul__(self, y): # real signature unknown; restored from __doc__
""" x.__imul__(y) <==> x*=y """
pass
def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable‘s items
# (copied from class doc)
"""
pass
def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass
def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x"""
pass
def __mul__(self, n): # real signature unknown; restored from __doc__
""" x.__mul__(n) <==> x*n """
pass
@staticmethod
# known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __reversed__(self): # real signature unknown; restored from __doc__
""" L.__reversed__() -- return a reverse iterator over the list """
pass
def __rmul__(self, n): # real signature unknown; restored from __doc__
""" x.__rmul__(n) <==> n*x """
pass
def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass
def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
"""
x.__setslice__(i, j, y) <==> x[i:j]=y

Use of negative indices is not supported.
"""
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" L.__sizeof__() -- size of L in memory, in bytes """
pass
__hash__ = None
list


功能源码

 






推荐阅读
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Python 异步编程:深入理解 asyncio 库(上)
    本文介绍了 Python 3.4 版本引入的标准库 asyncio,该库为异步 IO 提供了强大的支持。我们将探讨为什么需要 asyncio,以及它如何简化并发编程的复杂性,并详细介绍其核心概念和使用方法。 ... [详细]
  • 本文详细介绍 Go+ 编程语言中的上下文处理机制,涵盖其基本概念、关键方法及应用场景。Go+ 是一门结合了 Go 的高效工程开发特性和 Python 数据科学功能的编程语言。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • python的交互模式怎么输出名文汉字[python常见问题]
    在命令行模式下敲命令python,就看到类似如下的一堆文本输出,然后就进入到Python交互模式,它的提示符是>>>,此时我们可以使用print() ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • 本文将介绍由密歇根大学Charles Severance教授主讲的顶级Python入门系列课程,该课程广受好评,被誉为Python学习的最佳选择。通过生动有趣的教学方式,帮助初学者轻松掌握编程基础。 ... [详细]
  • 深入理解C++中的KMP算法:高效字符串匹配的利器
    本文详细介绍C++中实现KMP算法的方法,探讨其在字符串匹配问题上的优势。通过对比暴力匹配(BF)算法,展示KMP算法如何利用前缀表优化匹配过程,显著提升效率。 ... [详细]
  • 本文详细解析了如何使用Python语言在STM32硬件平台上实现高效的编程和快速的应用开发。通过具体的代码示例,展示了Python简洁而强大的特性。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 本文详细探讨了JDBC(Java数据库连接)的内部机制,重点分析其作为服务提供者接口(SPI)框架的应用。通过类图和代码示例,展示了JDBC如何注册驱动程序、建立数据库连接以及执行SQL查询的过程。 ... [详细]
  • 使用Pandas高效读取SQL脚本中的数据
    本文详细介绍了如何利用Pandas直接读取和解析SQL脚本,提供了一种高效的数据处理方法。该方法适用于各种数据库导出的SQL脚本,并且能够显著提升数据导入的速度和效率。 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • C++实现经典排序算法
    本文详细介绍了七种经典的排序算法及其性能分析。每种算法的平均、最坏和最好情况的时间复杂度、辅助空间需求以及稳定性都被列出,帮助读者全面了解这些排序方法的特点。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
author-avatar
手机用户2602934713
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有