string.sort(), sorted(), reverse, set(), list slice,list comprehension

一些小结 : 
The sort()method changes the ordering of lists in-place.
直接修改list顺序的方法.
>>> l=[1,2,3,2,3,4,1]
>>> l.sort()
>>> print(l)
[1, 1, 2, 2, 3, 3, 4]


The sorted() BIF sorts most any data structure by providing copied sorting.
修改list顺序的内建函数, 但是不修改list变量本身, 只是输出另一个list
>>> l=[1,2,3,2,3,4,1]
>>> sorted(l)
[1, 1, 2, 2, 3, 3, 4]
>>> print(l)
[1, 2, 3, 2, 3, 4, 1]


Pass reverse=True to either sort()or sorted()to arrange your data in descending order.
sort()和sorted()的反向排序参数reverse=True
>>> sorted(l,reverse=True)
[4, 3, 3, 2, 2, 1, 1]

When you have code like this: 
  new_l = []
  for t in old_l: 
    new_l.append(len(t))

rewrite it to use a list comprehension, 
like this: 

new_l = [len(t) for t in old_l]

list轮询处理产生另一个list的缩写
>>> l=[1,2,3,2,3,4,1]
>>> print([x*2 for x in l])
[2, 4, 6, 4, 6, 8, 2]


To access more than one data item from a list, use a slice. For example: 
my_list[3:6] 

accesses the items from index location 3 up-to-but-not-including index location 6.
list slice的访问方法, 不包含最大值索引.(索引从0开始), 反向索引从-1开始.
>>> l=[0,1,2,3,4,5,6,7]
>>> print(l[-3:-1])
[5, 6]
>>> print(l[0:3])
[0, 1, 2]


Createa setusing the set() factory function.
不带重复, 无序的list新类型set.
在没有set时, list可以使用以下方法去重复.
>>> l=[1,3,1,3,1,3]
>>> for i in l:
...   if i not in new_l:
...     new_l.append(i)
... 
>>> print(new_l)
[1, 3]

使用set()去重
>>> new_set=set(l)
>>> print(new_set)
{1, 3}

创建set类型的方法:
>>> new_set1=set()
>>> print(type(new_set1))
<class 'set'>

以下方法创建的是dict类型
>>> new_set2={}
>>> print(type(new_set2))
<class 'dict'>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值