Python学习笔记一

Python学习笔记一,第1张

实验环境:anaconda4.6.11

一、变量和简单数据类型 1.变量

这里和C++、Java一样,需要注意的就是变量名只能包含字母、数字和下划线,不能以数字开头,不能包含空格。

2.字符串

和Java中单引号引起字符,双引号引起字符串不同,python中,单引号和双引号引起的都是字符串,可以根据具体需要选择。另外介绍一些常用的字符串函数:

  1. title() upper() lower(),分别以首字母大写、所有字母大写、所有字母小写的方式显示每个单词
  2. rstrip() lstrip() strip(),分别剔除字符串末尾、开头、两端的空白
name = "Ada Lovelace"
print(name.title())
print(name.upper())
print(name.lower())

favorite_language = '   python    '
print(favorite_language.rstrip()+'#')
print(favorite_language.lstrip()+'#')
print(favorite_language.strip()+'#')

3.数字

数字类型有三种,整数、浮点数、复数。复数用的不多,不作介绍。
python可对整数执行加减乘除运算,另外**表示乘方运算

print(5**3)


浮点数要注意的是python2中的除法,如果除数和被除数都是整数,结果也是整数,比如3/2的结果不是1.5,而是整数1,这和Java相同;但是python3已经优化了这个问题,即使除数和被除数都是整数,结果也可以为小数。

print(3/2)

二、列表简介 1.列表是什么
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)


可以通过索引来列表中的单个元素,要注意的是索引是从0开始的。另外python提供了一种特殊语法,除了从正向0,1,2,3去访问元素,还可以以-1,-2,-3,-4逆向访问元素

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[3])
print(bicycles[-2])

2.修改、添加和删除元素

1)修改元素需要知道元素索引,通过重新赋值的方法去修改。

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)


2)添加元素有两种方法,一种是append()在末尾追加元素;一种是insert()在列表中间插入元素。

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.insert(1,'ducati')
print(motorcycles)


3)删除元素有三种方法,知道元素的索引可以用del()直接删除;把元素列表从列表删除后还想继续使用可以用pop(),pop()不含参数表示d出列表最末尾元素,pop()跟参数索引表示d出指定位置的元素;如果不知道索引,但是知道元素的值,就用remove()删除。

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
pop = motorcycles.pop()
print(pop)
print(motorcycles)

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
pop = motorcycles.pop(0)
print(pop)
print(motorcycles)

motorcycles = ['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

3.组织列表

1)使用sort()对列表进行永久性排序
sort()可以使字符列表按字母顺序排列,可以使数字列表按从小到大的顺序排列,当然也可以反着来,只要给sort()加一个参数reverse=True,sort()对列表的修改是永久性的。

figures = [1,3,2,5,4]
figures.sort()
print(figures)

figures = [1,3,2,5,4]
figures.sort(reverse=True)
print(figures)

2)使用sorted()对列表进行临时排序
sorted()用法和sort()一致,第一个的区别就是sorted()排序是临时的,不会修改原有的列表;第二个区别是sort()是方法,sorted()是函数,方法由对象进行调用,函数进行数据传递。

figures = [1,3,2,5,4]
print(figures)
print(sorted(figures))
print(figures)

3)倒着打印列表
要反转列表的元素顺序,可使用reverse()。

figures = [1,3,2,5,4]
print(figures)
figures.reverse()
print(figures)

4)确定列表的长度
len()可以获取列表的长度。

bicycles = ['trek','cannondale','redline','specialized']
print(len(bicycles))

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/737590.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存