关于列表的slice和islice,sort和sorte,heapq

来源:互联网 发布:java底层原理 编辑:程序博客网 时间:2024/06/07 20:24

# python3

a=[1,2,3,4]print(a[2:6])  # [3, 4]  对于这种切片,越界也不会报错print(a[10:12])  # [] 如上,不会报错,是空列表

def fib():    a, b = 0, 1    while True:        yield b        a, b = b, a + bf=fib()print(next(f))  # 1  print(next(f))  # 1print(next(f))  # 2print(next(f))  # 3print(next(f))  # 5

#islice

from itertools import islicedef fib():    a, b = 0, 1    while True:        yield b        a, b = b, a + bf=fib()print(list(islice(f,0,5)))  # [1,1,2,3,5]
# 对于任意可迭代对象,sorted返回的都是一个列表。sort是列表的一个方法,而sorted对所有可
# 迭代序列有效。列表的sort和sorted,sort改变原列表,而sorted生成一个新列表。
list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)]list2 = sorted(list1,key=lambda x:x[1],reverse=True)print list2  # [('lily', 95), ('david', 90), ('mary', 90), ('sara', 80)]print list1  # [('david', 90), ('mary', 90), ('sara', 80), ('lily', 95)]  # list1没有改变
list3 = [1,5,4,9,2,4]print(sorted(list3,key=lambda x:x))  # [1, 2, 4, 4, 5, 9]  list3.sort()print(list3)  # [1, 2, 4, 4, 5, 9]  # list3已经改变
import heapqnums=[1,2,4,8,9,3,]bigs = heapq.nlargest(2,nums)print(bigs)  # [9, 8]  # 还是列表smalls =heapq.nsmallest(2,nums)print(smalls)  # [1,2] # 还是列表


阅读全文
0 0
原创粉丝点击