Python学习笔记:列表简介

# -*- coding: utf-8 -*-
"""
Created on Sun Mar  1 14:19:24 2020

@author: 86159
"""
# #%% 可以把程序分成多个cell执行 用快捷键ctrl+enter
#%%
message="asd12 sd ASDFE"
print(message.title())#每个单词的首字母大写
#%%
message='  12  '
print(message)
print(message.lstrip())#去掉左边空格
print(message.rstrip())#去掉右边空格
print(message.strip())#去掉两侧空格
#%%
name="eric"
print("Hello "+name.title()+",would you like to learn some Python today")#字符串拼接
#%%
name="YanJie Sun"
print(name.lower())#把字符串中的所有字母全改为大写字母
print(name.upper())#把字符串中的所有字母全改为小写字母
print(name.title())#把字符串中每个单词的首字母改为大写字母
#%%
name="\talbert einstein\n"#\t tab键 制表符;\n 换行符
print(name.title().strip()+' once said,"A person who never made a mistake never tried anything new."')
#%%
print(3//2)#整除 结果为1
print(3/2)#结果为1.5
print(2**3)#**乘方 表示2的三次方 与pow(2,3)作用相同
print(pow(2,3))
print(1e5)#结果为 100000  1*10*10*10*10*10
#%%
print(round(3.451,1))#四舍五入,并截取到小数点后一位 结果为3.5
#%%
age=23
print(age)
print("hello"+str(age))#字符串直接和数字不能一起拼接,需要先转换为字符串,用函数str()
#%%
import this
#%%
bicycles=['1','2','3','abs']
print(bicycles[-1].title())#列表从右到左,索引为-1 -2 -3...
#%%
friends=['aa','bb','cc','dd','ee']
l=len(friends)#获取列表中元素个数,列表的长度
for i in range(l):
    mes=friends[i].title()
    print(mes+" hello")
#%%
friends=['aa','bb','cc','dd','ee']
i=-1
while i>-6:
    mes=friends[i].title()
    print(mes+" hello")
    i=i-1
#%%
friends=['aa',123,'cc','dd','ee']#可以有不同类型,但是无法比较大小
friends.append('ff')#在列表末尾插入新的字符串
friends.insert(2,'abs')#在列表索引2处插入新的字符串,原字符串及后面的都往右移一位
friends[0]='aaaa'
print(friends)
print(friends.index('cc'))#字符串'cc'在列表中的位置(索引)
print(friends.count('cc'))#字符串'cc'在列表中出现过几次
#print(max(friends))#不同类型之间无法比较大小
#print(min(friends))
print('bb'in friends)#判断 字符串'bb'在列表中 是否正确
print('bb'not in friends)#判断 字符串'bb'不在列表中 是否正确
#%%
friends=['aa',123,'cc','dd','ee','ff','gg']
del friends[0]#删除列表中索引为0的元素
print(friends)             
temp=friends.pop()#弹出栈顶元素(即最后一个),可以保存该元素的值
print(friends)
print(temp)
friends.pop(1)#弹出列表中索引为1的元素
print(friends)
friends.remove(123)
#从列表中移除值为123的元素(注意元素类型),该方法只删除第一个指定的值
#如果要删除的值在列表中出现多次,需要用循环来判断是否删除了所有这样的值
print(friends)
#%%
cars=['abc','aa','cc','dd']
print("输出原列表")
print(cars)
cars.sort()#按字母顺序的正序排序,永久性改变
print("输出按字母顺序正序排序后的列表")
print(cars)
cars.sort(reverse=True)#按字母顺序的逆序排序,永久性改变
print("输出按字母顺序逆序排序后的列表")
print(cars)
#%%
cars=['abc','aa','cc','dd']
tt=sorted(cars)#按字母顺序的正序排序,临时排序,不会改变原列表中的元素顺序
print("输出按字母顺序正序排序后的列表")
print(tt)
tt=sorted(cars,reverse=True)#按字母顺序的逆序排序,临时排序,不会改变原列表中的元素顺序,向函数sorted传递参数reverse=True
print("输出按字母顺序逆序排序后的列表")
print(tt)
print("输出原列表")
print(cars)
#%%
cars=['abc','aa','cc','dd']
print("输出原列表")
print(cars)
cars.reverse()#只是反转列表元素的排列顺序,不是按字母顺序排序,用两次方法reverse就可变回原列表
print("倒着打印列表中的元素")
print(cars)
发布了78 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37209590/article/details/104620618