python中列表和元组的操作(结尾格式化输出小福利)

时间:2024-10-12 23:33:37

一. 列表

1. 查

names = "YanFeixu *fan"
names_1 = ["YanFeixu"," *fan","Zhangsan"] print(names)
print(names_1[0],names_1[2])
print(names_1[1:2]) # 切片
print(names_1[2]) # 切片
print(names_1[-1]) # 切片
print(names_1[-2:]) # 切片

python中列表和元组的操作(结尾格式化输出小福利)

2. 增

names_1 = ["YanFeixu"," *fan","Zhangsan"]
names_1.append("zhansgan") # 新增
names_1.insert(1,"Lisi") # 插入索引为1的前面 print(names_1)

python中列表和元组的操作(结尾格式化输出小福利)

3. 改

names_1 = ["YanFeixu"," *fan","Zhangsan"]
names_1[2] = "Zhuli" print(names_1)

python中列表和元组的操作(结尾格式化输出小福利)

4. 删

names_1 = ["YanFeixu"," *fan","Zhangsan","Zhuli"]
names_1.remove("Zhangsan") # 删除的第一种方法
del names_1[1] # 删除的第二种方法
names_1.pop() # 默认删除最后一个 print(names_1)

python中列表和元组的操作(结尾格式化输出小福利)

5. 列表的方法

# 方法
names_1 = ["YanFeixu"," *fan","Zhangsan","Zhuli","Zhuli"] print(names_1.index("Zhuli")) # 序号
print(names_1 [names_1.index("Zhuli")]) # 把Zhuli打印下来
print(names_1.count("Zhuli")) # 统计一下有几个Zhuli names_1.reverse() # 把列表反转,也就是把序号颠倒
print(names_1) names_1.sort() # 把列表按字母排序,先是符号,再是数字,再是字母
print(names_1) names_2 = [1,2,3,4] # 扩展的方法,列表name_1和name_2合并了
names_1.extend(names_2)
print(names_1,"+",names_2)

python中列表和元组的操作(结尾格式化输出小福利)

import copy
# 方法
names_1 = ["YanFeixu"," *fan","Zhangsan",["Wangwu","Zhouliu"],"Zhuli","Zhuli"]
names_2 = names_1.copy() # 浅copy,只复制第一层,它变我不变(因为已经复制下来了),其余层它变我也变,外面是第一层**
print(names_1) names_1[2] = "张三"
names_1[3][0] = "王五"
print(names_2) names_1[2] = "张三"
names_3 = copy.deepcopy(names_1) # 深copy,就是克隆一份,具有自己单独的内存地址,两者完全不相干设,他变我不变
print(names_3)

python中列表和元组的操作(结尾格式化输出小福利)

二、元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法names = ("YanFeixu","jack","eric")

它只有2个方法,一个是count,一个是index。

小福利:

python中三引号的作用:

1 多行注释


print('Hello world!')
"""
这是一个
多行注释
注释,
###
"""

2 按照原格式输出文本(也就是格式化输出)

a = """ ###pandas features a number of
fnctions for reading 'tabular data' as
a DataFrame object. Such as , read_csv ...&&&;;;'''hello'''
"""
print(a)

输出结果:

python中列表和元组的操作(结尾格式化输出小福利)

3.格式化输出的案例:

案例(1)

name  = input("name:")
age = input("age:")
job = input("job")
# 此处的三引号是格式化输出,不是注释!
info = '''------info of %s------
Name: %s
Age : %s
Job: %s
''' % (name,name,age,job) print(info)

输出结果:

name:hzangsan
age:12
job:da
------info of hzangsan------
Name: hzangsan
Age : 12
Job: da

案例(2)


name_1 = input("name_1:")
age_1 = input("age_1:")
job_1 = input("job_1:") info_1 = '''-----info of {name}------
Name: {name}
Age: {age}
Job: {job}
'''.format(name = name_1,
age = age_1,
job = job_1) print(info_1)

输出结果:

name_1:zhansan

age_1:12

job_1:nishi

-----info of zhansan------

Name: zhansan

Age: 12

Job: nishi

此处有一个关于format的知识点:

username = input("username:")
print ("welcome {name} to our school".format(name = username ))

输出结果:

python中列表和元组的操作(结尾格式化输出小福利)