Python数据结构的常用方法

一、集合的常用方法

二、字典

#使用fromkeys创建key为[1,2,3,4]
dict.fromkeys([1,2,3,4],0) 
{1: 0, 2: 0, 3: 0, 4: 0}
#使用get查询值,可以使用default参数设置当key不存在时的返回值
print(adict.get("list",1))
print(adict.get("list3"))
print(adict.get('list3',1))
[3]
None
1
#使用items获取所有的key value对.是一个序列
print(adict.items())
dict_items([('list', [3]), ('interLM', 'LLM'), (1, 'summer camp'), (2, 'internLM')])
#使用items获取所有的key
print(adict.keys())
dict_keys(['list', 'interLM', 1, 2])
#使用items获取所有的values
print(adict.values())
dict_values([[3], 'LLM', 'summer camp', 'internLM'])

三、字符串

astring = 'InternLM'
bstring = "Intern'LM'"#当字符串内有'时,可以使用"
print(list(astring))
['I', 'n', 't', 'e', 'r', 'n', 'L', 'M']
#获取字符串中第3个元素
print(astring[2])
#获取字符串中倒数第二个元素
print(astring[-2])
#获取字符串中的第二个到第四个字符组成的子串
print(astring[1:4])
t
L
nte

#字符串的方法实在太多,在在这里我们只取几个比较常用的方法作为示例。
text = "Success is not final, failure is not fatal: It is the courage to continue that counts."
#首先我们把这句话中所有的字母都转换为小写
text = text.lower()
print(text)
#再用replace把所有的标点符号去掉
text = text.replace(','," ").replace(':'," ").replace('.'," ")
print(text)
#再用split把这句话拆成词组成的列表
word_list = text.split(" ")
print(word_list)
#再用join函数用,把这个列表拼会一个字符串
print(','.join(word_list))
success is not final, failure is not fatal: it is the courage to continue that counts.
success is not final  failure is not fatal  it is the courage to continue that counts 
['success', 'is', 'not', 'final', '', 'failure', 'is', 'not', 'fatal', '', 'it', 'is', 'the', 'courage', 'to', 'continue', 'that', 'counts', '']
success,is,not,final,,failure,is,not,fatal,,it,is,the,courage,to,continue,that,counts,

在做LLM开发时避不开对字符串做格式化输出,即指定一个模板把变量放入模板中。接下来我们介绍两种常见的易于实现复杂格式化输出的方法。

第一种为使用字符串的.format()方法,并在在字符串中需要插入值的地方用{}代替,{}也可以加入变量名,方便赋值。

#我们用字典存储一个学生的信息,假设小明是实战营第二期的
#我们需要在输出的时候将他转化成一句话
#小明在12岁的时候参加了书生浦语实战营第二期, 最终获得了优秀学员。
student = {'name':'小明','age':12,'class':"书生浦语实战营第二期",'grade':'优秀学员'}
string_templet = '{}在{}岁的时候参加了{},获得了{}。'#做一个模板
print(string_templet.format(student['name'],student['age'],student['class'],student['grade']))
#在模板中没有指定变量名时, .format方法就按照顺序来填入值下面来演示一下加入变量名后会有什么不同
string_templet2 = "{name}在{age}岁的时候参加了{course},获得了{grade}。"#做一个模板
print(string_templet2.format(grade=student['grade'],name=student['name'],age=student['age'],course=student['class']))
#使用这种变量方法命名时, format就可以忽略format参数中的顺序了,对于一些特别长变量特变多的模板来说更清晰。
小明在12岁的时候参加了书生浦语实战营第二期,获得了优秀学员。
小明在12岁的时候参加了书生浦语实战营第二期,获得了优秀学员。

第二种方法我们使用python在3.6推出的f-sting功能,只需在字符串开头加上f,该字符串中的{}中的python代码就会被评估。

student = {'name':'小明','age':12,'class':"书生浦语实战营第二期",'grade':'优秀学员'}
string_out = f"{student['name']}在{student['age']}岁的时候参加了{student['class']},获得了{student['grade']}。"
print(string_out)
print(f"{1+2}")
小明在12岁的时候参加了书生浦语实战营第二期,获得了优秀学员。
3

python中的if语句为:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
  • 如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
  • 如果 "condition_1" 为False,将判断 "condition_2"
  • 如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
  • 如果 "condition_2" 为False,将执行"statement_block_3"块语句

接下来我们用if语句完成一个成绩等级判定的功能:

  • [90,100] A
  • [80,90) B
  • [70,80) C
  • [60,70) D
  • [0,60) F
score = 80
if score>=90:
    print('A')
elif score>=80:
    print('B')
elif score>=70:
    print('C')
elif score>=60:
    print('D')
else:
    print('F')
B

Python while循环语句语法

while condition:
    statement

以上是while语句的形式,当condition为True时,while会执行statement然后再判断condition,直至condition变为False才会结束循环

#用while语句求100以内数字的和
i=0
res = 0
while i<100:
    res+=i
    i+=1
print(res)
4950

Python中for语句的语法为

for <variable> in <sequence>:
    <statements>
else:
    <statements>

for循环可以遍历任何可迭代的对象,比如一个列表。

for st in ['InternLM','LLM','transformer','Shanghai']:
    print(st)
InternLM
LLM
transformer
Shanghai

提到for循环就不能不提经常与它一起出现的range(start,stop,step)函数,他会生成一个可迭代的对象,以step步长生成[start,stop)。可以只写一个stop,默认从0开始。

for i in range(5):
    print(i)
0
1
2
3
4

2.10.3 列表推导式

#列表推导式是一种很方便的写法,但我们在这不作为重点,大家可以看着例子应该就能理解列表推导式的写法
#找出1-100内能被3整除的数
print([i for i in range(1,101) if i%3==0])
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

python定义函数的关键字为def

def 函数名(参数列表):
    函数体
#定义一个打招呼的函数,别忘了冒号
def hello(name):
    out = 'Hello '+name
    print(out)
hello('InternLM2')
Hello InternLM2
#注意,函数中定义的变量为局部变量,只有函数内能访问到,这就是变量的作用领域
print(out)
#当我们尝试使用变量out时就会报错,提示out没有被定义
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~\AppData\Local\Temp\ipykernel_13796\2663579863.py in <module>
      1 #注意,函数中定义的变量为局部变量,只有函数内能访问到,这就是变量的作用领域
----> 2 print(out)
      3 #当我们尝试使用变量out时就会报错,提示out没有被定义


NameError: name 'out' is not defined
  • 参数是可变对象时,传参时传递的是索引,在函数中修改该参数会作用于原对象
  • 参数是不可变对象时,传参时会自动复制,在函数中修改该参数不会作用于原对象
def update(number,alist):
    number = 3
    alist[1] = 3
    print("number: ", number)
    print("alist: ", alist)
    print("id(number)",id(number))
    print("id(alist)",id(alist))
a = 2
b = [1,1,1]
print(id(a))
print(id(b))
update(a,b)
140710873047488
2531815942344
number:  3
alist:  [1, 3, 1]
id(number) 140710873047520
id(alist) 2531815942344

可以看到在update函数内修改了number和alist,函数外面的整数a没有被修改,但是列表b被修改了。 这就是python函数在传参时候的特征导致的。通过使用id()函数可以获取对象在内存中的地址可以看到number与a的id不同,他们是两个对象了。但是alist与b的id相同,说明他们两在内存中指向的是同一个对象。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sɪʟᴇɴᴛ໊ོ5329

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值