[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
在Python中,切片是列表、元组或者字符串中常见用法,然而对一些新手而言,有时候含有切片的代码可读性并不是非常友好。下面就说一说Python中切片的具体用法。
在Python中,切片的使用方式为[起始位置 : 结束位置 : 步长]
,代表着从起始位置到结束位置根据步长所得到的全部元素。其中,起始位置、结束位置、步长三个属性均有默认值,当不指定其具体值时,Python就会使用其默认值,它们的默认值分别为0,、列表或元组长度、1。
值得注意的几点是:
1、当起始位置为负数时,比如起始位置为 -k 时,此时表示取最后列表、元组或字符串中的最后k个元素。
2、当步长为负数时,表示从后往前开始计数,其绝对值仍然是间隔。
下面给出几个demo看一下。
rlist=list(range(10)) #生成的是[0,1,2,3,4,5,6,7,8,9] print(rlist[2:8])
#从第3个元素开始,到第8个元素结束 print(rlist[:5]) #如果冒号前面没写的话,代表从0开始取的 print(rlist[4:])
#如果冒号后面没写的话,代表取到最后 print(rlist[:]) #如果冒号前后都没写的话,代表取全部 b = a[i:j]
#表示复制a[i]到a[j-1],以生成新的list对象 a = [0,1,2,3,4,5,6,7,8,9] b = a[1:3] #[1,2]
#当i缺省时,默认为0,即 a[:3]相当于 a[0:3] #当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
#当i,j都缺省时,a[:]就相当于完整复制一份a b = a[i:j:s] #表示:i,j与上面的一样,但s表示步进,缺省为1.
#所以a[i:j:1]相当于a[i:j] #当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1 #所以a[::-1]相当于
a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。
下面是一个趣味题:
#判断一个字符串是否是回文,即:字符串和它反转后的字符串是否相等,如果相等就是回文。 s='上海自来水来自海上' # 回文算法,反过来倒过去都一样 for
i in range(10): s = input('请输入一个字符串:') if len(s)<2: print('字符串长度必须大于2') elif
s==s[::-1]: #.reverse()方法是列表中的方法,字符串中没有,因此只能用切片方法 print('是回文') else:
print('不是回文')
结束,感谢阅读!如果有误,请指正!