python合集(4)------------列表与元组

本文详细介绍了Python中的序列类型,特别是列表的创建、操作和方法,包括连接、成员、索引、切片、循环等。还讨论了元组的特性,并展示了列表的增删改查操作。最后,通过一个云主机管理系统实例展示了列表的运用。
摘要由CSDN通过智能技术生成

1.序列

成员有序排列的,且可以通过下标偏移量访问到它的一个或者几个成员,这类类型统称为序列。
序列数据类型包括:
字符串,列表,和元组类型。
特点: 都支持下面的特性:
索引与切片操作符
成员关系操作符(in , not in)
连接操作符(+) & 重复操作符(*)

2.列表

数组: 存储同一种数据类型的集和。scores=[12,95.5]
列表(打了激素的数组): 可以存储任意数据类型的集和

2.1列表的创建

创建空列表
li = []
创建一个包含元素的列表,元素可以是任意类型,
包括数值类型,列表,字符串等均可, 也可以嵌套列表。
list = [“霄壤”, 4, ‘god’]
list = [[‘老铁’, 999], [‘l老铁’,666]]

2.2列表的基本特性

2.2.1 连接操作符和重复操作符

print([1, 2] + [3, 4]) # :[1, 2, 3, 4]
print([1, 2] * 3) #: [1, 2, 1, 2, 1, 2]

2.2.2 成员操作符

print(1 in [1, 2, 3]) # True 
print(1 in ["a", True, [1, 2]])  # True bool值,1--->True;0--->False
print(1 in ["a", False, [1, 2]])  #False
print(1  not in ["a", False, [1, 2]])  #True

2.2.3. 索引

list = [7, 8, 9, [2, 'xx', 6]]
print(list[0])  # 7
print(list[-1]) # [2, 'xx',6 ]
print(list[-1][2])  # 6
print(list[3][-1])  # 6

2.2.4. 切片

list = ['172', '25', '6', '1']
print(list[1:2])
print(list[1:])
print(list[:3])
print(list[::-1])
print("-".join(li[0:][::-1]))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/列表.py
['25']
['25', '6', '1']
['172', '25', '6']
['1', '6', '25', '172']
1-6-25-172

2.2.5. for循环

names = ["天龙", '盘龙', '真龙']
for name in names:
    print(f"龙族族长是:{name}")

2.3列表的常用方法

在这里插入图片描述

**2.3.1. 增加**
 *追加*:在列表后添加
list = ['w','e','s','t','o']
list.append('s') #添加单个元素
print(list) # ['w', 'e', 's', 't', 'o', 's']
*在列表开头添加*
list = ['w','e','s','t','o']
list.insert(0, 'linux')#:可根据索引任意位置添加
print(list) #['linux','w', 'e', 's', 't', 'o', 's']
3). 一次追加多个元素
li = [1, 2, 3] # 添加4, 5, 6
li.extend([4, 5, 6])
print(li) ##[1,2,3,4,5,6]

2.3.2. 修改: 通过索引和切片重新赋值的方式。
list = [1, 2, 3]
list[0] = ‘xaio’ #列表中第0个元素改为‘xaio’ 
list[2] = ‘haha’ #列表中第2个元素改为‘haha’
print(list) #['xiao', 2, 'haha']

list = [1, 2, 3]
list[:2] = ['cat', 'westos']
print(list) #[‘cat’,‘westos’,3] 

2.3.3. 查看: 通过索引和切片查看元素。 查看索引值和出现次数。
list = [1, 2, 3, 1, 2, 3]
print(list.count(2)) # 2
print(list.index(1)) # 0
print(list.count(1)) # 2

2.3.4. 删除
**根据索引删除**
list = [1, 2, 3]
delete_num = list.pop(0):将pop方法的结果(列表中的首位)存储到delete_num变量中
print(list)
print(f"删除的元素是:{delete_num}")

**value值删除**
list = [1, 2, 3]
list.remove(1)
print(list)  #[2, 3]

**全部清空**
list = [1, 2, 3]
list.clear()
print(list) #[]

2.3.5. 其他操作
list = [99, 33, 88]
list.reverse() #倒序
print(list) #[88, 33, 99]
li.sort(reverse=True):排序倒序,sort默认为顺序
print(list) #[99, 88, 33]

3.元组(tuple: 不能修改元素)

  • 特性: 连接&重复操作符、成员操作符、索引&切片
**3.1元组的创建**
tuple1 = () # 空元组
tuple2 = (1,) # 重要(易错点):元组只有一个元素时一定要加逗号
print(tuple2, type(tuple2))
print(tuple1, type(tuple1))
tuple3 = (1, True, [2,3,4]) #仍然是元组类型
print(tuple3, type(tuple3))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/列表.py
(1,) <class 'tuple'>
() <class 'tuple'>
(1, True, [2, 3, 4]) <class 'tuple'>

**3.2元组基本特性**
**3.2.1连接操作符和重复操作符**
print((8, 9, 7) + (6,)) #(8, 9, 7, 6)
print((9, 8, 7) * 2) # (9, 8, 7, 9, 8, 7)

**3.2.2成员操作符**
print(1 in (1, 2, 3))  #True
print(1  not in (1, 2, 3)) #False

**3.2.3索引,切片**
t = (5,6,7,8,9)
print(t[-1])  # 9
print(t[:3])  #(5, 6, 7)
print(t[0:])  #(5, 6, 7,8,9)
print(t[0:3]) #(5, 6, 7)
print(t[::-1]) #(9, 8, 7, 6, 5)
查看: 通过索引和切片查看元素。 查看索引值和出现次数。
t = (1, 2, 3, 1, 2, 3)
print(t.find(1))  # 0
print(t.count(2)) # 2
print(t.index(3)) # 2
**3.4.命名元组**
***命名元组又称namedtuple,对比于tuple,namedtuple功能更为强大。***
from collections import namedtuple #:从collections模块中导入namedtuple工具
namedtuple1 = ('卡维尔', 22, '亚特兰蒂斯')
勇者 = namedtuple('勇者', ('姓名','年龄', '种族')) #:创建命名元组对象勇士
勇者1 = 勇者('卡维尔', 22, '亚特兰蒂斯')  #:传值到命名元组
print(f'{勇者1}') #: 打印命名元组
print(f'{勇者1.姓名}') #:获取命名元组指定的信息
结果:
勇者(姓名='卡维尔', 年龄=22, 种族='亚特兰蒂斯')
卡维尔

4. is和==的区别

1). Python中对象的三个基本要素,分别是:id(身份标识)、type(数据类型)和value(值)。
2). is和==都是对对象进行比较判断作用的,区别:
==用来比较判断两个对象的value(值)和数据类型(type)是否相等;(type和value)
is也被叫做同一性运算符, 会判断id是否相同;(id, type 和value)

5.深拷贝与浅拷贝

浅拷贝: 对另外一个变量的内存地址的拷贝,这两个变量指向同一个内存地址的变量值。(li.copy(), copy.copy())
公用一个值;
这两个变量的内存地址一样;
对其中一个变量的值改变,另外一个变量的值也会改变;
深拷贝: 一个变量对另外一个变量的值拷贝。(copy.deepcopy())
两个变量的内存地址不同;
两个变量各有自己的值,且互不影响;
对其任意一个变量的值的改变不会影响另外一个;

可变数据类型(可增删改的): list 不可变数据类型:数值,str, tuple, namedtuple`

test:列表练习题:编写云主机

“”"
编写一个云主机管理系统:
- 添加云主机(IP, hostname,IDC)
- 搜索云主机(顺序查找)
- 删除云主机
- 查看所有的云主机信息
“”"
from collections import namedtuple
menu = “”"
云主机管理系统
1). 添加云主机
2). 搜索云主机(IP搜索)
3). 删除云主机
4). 云主机列表
5). 退出系统
请输入你的选择: “”"

hosts = [ ]
Host = namedtuple('Host',('ip','id','hostname'))
id = 0
while True:
    choice = input(menu)
    if choice == "1":
        print('add vm hosts'.center(50,'*'))
        ip = input("ip:")
        id +=1
        hostname = input("hostname:")
        host1 = Host(ip,id,hostname)
        hosts.append(host1)
        print( f"add {host1} success" )
        with open('hosts.json','w') as f :
            json.dump(hosts,f)
    elif choice == "2":
        print('search vm hosts'.center(50,'*'))
        search_name = input( 'input hostname: ')
        for host in hosts:
            if search_name == host:
                 print(f'search {host.ip}\t{host.id}\t{host.hostname} success')
                 break
        else:
             print(f' {host.id}\t{host.ip}\t{host.hostname} not found')
    elif choice == '3':
        print('remove vm hosts'.center(50,'*'))
        delete_id = input('input vm id:')
        for host in hosts:
            if delete_id == host:
                hosts.remove(host)
                print(f'remove vm hosts {host.hostname} success')
                break
        else:
            print(f'{delete_id} not found ')
    elif choice == '4':
        print('list  vm  hosts'.center(50,'*'))
        print(f'IP\t\t\tID\t\tHOSTNAME')
        count = 0
        for host in hosts:
            count += 1
            with open('/home/kiosk/PycharmProjects/pythonProject/6-18/hello.json') as f :
                hosts= json.loads(f)
            print(f'{host.ip}\t{host.id}\t{host.hostname} ')
        print(f'vm hosts: {count}')
    elif choice == '5':
        print('eixt system'.center(50,'*'))
        exit()
    else:
        print('please input your right choice')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值