无厘头的基础类型基础

mac2025-06-19  3

其他操作:

print(type(None)) # <class 'NoneType'> print(bool(0)) # False print(bool(None)) print(bool("")) print(bool([])) print(bool({})) print(bool(())) # 原因:创建的列表自创建之后便存在,会占用所有必要内存来存储其值。 mylist = [ ix for ix in range(10, 20) ] # 结果就是一个列表 print(mylist)# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] mygen = ( ix for ix in range(10, 20) )# 返回的是生成器对象: print(mygen)# <generator object <genexpr> at 0x00000279A3966E48>

字符串的操作:

message = "what do you like?" response = 'spam' # 字母全部大写 print(response.upper()) # SPAM # 第一个单词的首字母大写 print(message.capitalize()) # What do you like? # 全部单词的首字母大写 print(message.title()) # What Do You Like? return_value = print('abc') # abc print(return_value) # None fox = "tHe qUICk bROWn fOx. 000 " print(fox.upper()) # 全部字母大写 print(fox.lower()) # 全部字母小写 print(fox.title()) # 每个单词的首字母大写 print(fox.capitalize()) # 第一个字母大写,其他的小写 print(fox.swapcase()) # 每个单词的首尾字母大写 print(fox.strip()) # 删除两边空格 print(fox.rstrip()) # 要仅删除右侧或左侧的空间 print(fox.lstrip()) print(fox.strip('0')) # 删除空格以外的0字符 print(fox.center(50)) # 给定数量的空格内将给定字符串居中 print(fox.ljust(30)) # 左对齐或右对齐中的给定长度的空格字符串 print(fox.rjust(30))

数字的操作:

# 返回一个分子和一个分母 x = 0.125 print(x.as_integer_ratio()) # (1, 8)

列表的排序:

l = [4, 2, 7, 4, 9, 1] print(sorted([4, 2, 7, 4, 9, 1])) # 直接排序后返回排序结果 l.sort() # 只进行排序操作,不返回排序结果 print(l) print(sorted(['pear', 'apple', 'orange', 'cranberry'])) # 输出: # [1, 2, 4, 4, 7, 9] # [1, 2, 4, 4, 7, 9] # ['apple', 'cranberry', 'orange', 'pear'] data=[{'first':'Guido', 'last':'Van Rossum', 'YOB':1956}, {'first':'Grace', 'last':'Hopper', 'YOB':1906}, {'first':'Alan', 'last':'Turing', 'YOB':1912}] # 以字典为值 result = sorted(data, key=lambda item: item['YOB']) print(result) # 输出: # [ # {'first': 'Grace', 'last': 'Hopper', 'YOB': 1906}, # {'first': 'Alan', 'last': 'Turing', 'YOB': 1912}, # {'first': 'Guido', 'last': 'Van Rossum', 'YOB': 1956} # ] adict = {'a': 24, 'g': 52, 'i': 12, 'k': 33} result = sorted(adict.items( ), key = lambda x: x[1]) # 有返回值 print(dict(result)) # 输出:{'i': 12, 'a': 24, 'k': 33, 'g': 52} alist = [{'name': 'a', 'age': 20}, {'name': 'b', 'age': 30}, {'name': 'c', 'age': 25}] alist.sort(key = lambda x: x['age'], reverse = True) # 无返回值 print(alist) # 输出:[{'name': 'b', 'age': 30}, {'name': 'c', 'age': 25}, {'name': 'a', 'age': 20}] N = 100 # 把1到99的数值,放到矩阵中,每行三个数数值 print([[x for x in range(1, 100)][i:i + 3] for i in range(0, 100, 3)])

列表或元组——》转化为字典:

# 列表(以元组为值) dict2 = dict([('name','earth'),('port','80')]) # 元组(以列表为值) dict1 = dict((['name','earth'],['port','80'])) print(dict1) print(dict2) # 输出: # {'name': 'earth', 'port': '80'} # {'name': 'earth', 'port': '80'}

字典的操作:

primes = {2, 3, 5, 7} odds = {1, 3, 5, 7, 9} # 两个字典中的出现的值 print(primes | odds) # {1, 2, 3, 5, 7, 9} print(primes.union(odds)) # 两个字典中一样的值 print(primes & odds) # {3, 5, 7} print(primes.intersection(odds)) # 对比primes字典,odds字典中没出现的值 print(primes - odds) # {2} print(primes.difference(odds)) # 两个字典中不一样的值 print(primes ^ odds) # {1, 2, 9} print(primes.symmetric_difference(odds)) # 在多个字典中找到公共键 from functools import reduce from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))} s2 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))} s3 = {x: randint(1, 4) for x in sample('abfcdrg', randint(1, 5))} print(s1)#{'b': 2, 'r': 2, 'c': 1} print(s2)#{'a': 2, 'f': 1, 'c': 2, 'g': 4} print(s3)#{'c': 3} result = reduce(lambda x, y: x & y, map(dict.keys, [s1, s2, s3])) print(result)#{'c'} dict_keys = map(dict.keys, [s1, s2, s3]) # 获取字典的Keys print(*dict_keys) # 输出 dict_keys(['b', 'r', 'c']) dict_keys(['a', 'f', 'c', 'g']) dict_keys(['c'])

创建迭代器:

1.迭代器是一个可以记住遍历的位置的对象。 2.迭代器有两个基本的方法:iter()next()3.字符串,列表,字典或元组对象都可用于创建迭代器 4.内置函数和自定义函数也可用于创建迭代器 it=iter(range(10)) # 列表 print(next(it)) it_01 = iter([1,2,3]) # 列表 print(next(it_01)) it_02=iter((1,2,3)) # 元组 print(next(it_02)) it_03=iter({1:"a",2:"b",3:"c"}) # 字典 print(next(it_03)) it_04 = iter({"a":1,"b":2,"c":3}) # 字典 print(next(it_04)) it_05=iter(set((1,2,3))) # 元组 print(next(it_05)) it_06=iter("xyz") # 字符串 print(next(it_06)) m = map(str, range(10)) print(m) # <map object at 0x00000295EA178BC8> print(next(m)) # 0 print(list(m)) # ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def get_letter(i): return chr(ord('a')+i) m=map(get_letter, range(10)) print(m) # <map object at 0x0000017E1B5E8B48> print(next(m)) # a print(list(m)) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

迭代器的操作:

from itertools import count factors = [2, 3, 5, 7] # 找出不是2,3,5,7倍数的值 G = (i for i in count() if all(i % n > 0 for n in factors)) for val in G: print(val, end=' ') if val > 40: break # 输出: # 1 11 13 17 19 23 29 31 37 41

生成器的操作:

def substituter(seq, substitutions): for item in seq: if item in set(substitutions): yield substitutions[item] else: yield item s = 'hello world and everyone in the world' subs = {'hello': 'goodbye', 'world': 'galaxy'} for word in substituter(s.split(), subs): print(word) # 输出: # goodbye # galaxy # and # everyone # in # the # galaxy def gen(): # 【https://www.oreilly.com/learning/a-whirlwind-tour-of-python】 for n in range(12): yield n ** 2 G1 = (n ** 2 for n in range(12)) # 两种构造等效生成器的方法 G2 = gen() # 两种构造等效生成器的方法 # *,可以用来收集和分配参数。G1是一个生成器对象,*G1可以将其中的所有参数提取出来,分配给print() print(*G1) print(*G2) print(list(G1)) print(list(G2)) # 输出: # 0 1 4 9 16 25 36 49 64 81 100 121 # 0 1 4 9 16 25 36 49 64 81 100 121 # [] # []

扩展

用sublime编译器,没报错,风扇几秒后慢慢的飞了 from itertools import count factors = [2, 3, 5, 7] # 找出不是2,3,5,7倍数的值 G = (i for i in count() if all(i % n > 0 for n in factors)) # print([i for i in G if i>40]) for val in G: print(val, end=' ') if val > 40: break

扩展列表操作

# coding=utf-8 # 【https://www.ibm.com/developerworks/cn/analytics/library/ba-on-demand-data-python-2/index.html】 import math from itertools import chain, islice, groupby, cycle from functools import reduce def get_letter(i): return chr(ord("a") + i) def sum_of_squares(acc, i): return acc + i ** 2 def notby2or3(n): return math.gcd(n, 2) == 1 and math.gcd(n, 3) == 1 def forth_back_forth(n): yield range(n) yield range(n, 0, -1) yield range(n) # 无限迭代器 def zigzag_iters(period): while True: yield range(period) yield range(period, 0, -1) # 级联迭代器 def zigzag(period): while True: yield from range(period) yield from range(period, 0, -1) # https://www.ibm.com/developerworks/cn/analytics/library/ba-on-demand-data-python-2/Picture1.png def divide_by_3(n): return n // 3 # 迭代器表达式(自定义函数) # print(list(map(get_letter, range(10)))) # 输出:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # 生成器表达式(自定义函数) # print(list(((get_letter(i) for i in range(10))))) # 输出:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # 迭代器表达式(内置函数) # print(list(map(str, range(10)))) # 输出:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # 生成器表达式(内置函数) # print(list((chr(ord("a") + i) for i in range(10)))) # 输出:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # 实现数值相加 # print(sum(range(20, 30))) # 输出:245 # 实现每个数值平方后相加 # print(reduce(sum_of_squares, range(10))) # 输出:285 # 从1到10 打印出不是2,3的公约数 print(list((n for n in range(1, 20) if math.gcd(n, 2) == 1 and math.gcd(n, 3) == 1))) # 从1到10 打印出不是2,3的公约数(自定义函数) print(list(filter(notby2or3, range(1, 20)))) # 连接两个迭代器 print(list(chain(range(5), range(5, 0, -1), range(5)))) # 连接多个迭代器 print(list(chain(*forth_back_forth(3)))) # 无限迭代器----------------------------- it = chain.from_iterable(zigzag_iters(2)) print(next(it)) # 0 print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 1 print(next(it)) # 0 # 级联迭代器-------------------------------------------------------- print(list(islice(zigzag(5), 0, 20))) # 切片:打印下标0到19 # 输出:[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1] print(list(islice(zigzag(5), 1, 20))) # 切片打印下标1到19 # 输出:[1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1] print(list(islice(zigzag(5), 0, 20, 2))) # 切片:打印从下标0到19,步长2 # 输出:[0, 2, 4, 4, 2, 0, 2, 4, 4, 2] it = groupby(range(12), divide_by_3) print(next(it)) print(next(it)) print(next(it)) print(next(it)) for quadrant, group_it in groupby(range(12), divide_by_3): """ 输出: 象限中的项目: 0 0 1 2 象限中的项目: 1 3 4 5 象限中的项目: 2 6 7 8 象限中的项目: 3 9 10 11 """ print('\n象限中的项目:', quadrant) for i in group_it: print(f"\t{i}", end = " ") # 切片:打印下标0到31 print("\n", list(islice(cycle(range(12)), 32))) # islice:把传入的一个序列无限重复下去 # 输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7]
最新回复(0)