13.有两个字符串列表,a和b,每个字符是由逗号分隔的一些字符,(升级题)尽量做得支持扩展
a = [
'a,1',
'b,3,22',
'c,3,4'
'f,5'
]
b=[
'a,2',
'b,4',
'd,2'
'e,12'
]
按每个字符串的第一个值,合并a和b到c
c = [
'a,1,2',
'b,3,22,4',
'c,3,4',
'd,2',
'e,12',
'f,5'
]
# 老师的方法,老师善用字典,添加增加 get 方法 遍历 推导式的对应很厉害
# 老师的方法,老师善用字典,添加增加 get 方法 遍历 推导式 dic = { i[0]:i for i in d}#{'a': 'a,1', 'b': 'b,3,22', 'c': 'c,3,4', 'f': 'f,5'} l = [] for em in b: #遍历好 if dic.get(em[0]): # 如果在里面 则是真 # em += dic[em[0]][1:] # l.append(em) # 我的垃圾思想 dic[em[0]]+=em[1:]# 添加值 切片一下 else: # l.append(dic) # l.append(em) dic[em[0]] = em #不在里面 添加键值对 # l.append(dic) #这里蒙住了 print(dic.values())#dict_values(['a,1,2', 'b,3,22,4', 'c,3,4', 'f,5', 'd,2', 'e,12']) print(list(dic.values()))#['a,1,2', 'b,3,22,4', 'c,3,4', 'f,5', 'd,2', 'e,12']
#我做的,每次都弄成 reduce 不会用 乱用 做出来了才是 好方法
from functools import reduce # i = 0 lis = [] # def func(x,y): # x=12345 for i in range(len(x)): if x[i][0] == y[i][0]: # print(x[i][0]) lis.append(x[i]+y[i][1:]) else: lis.append(x[i]) lis.append(y[i]) # return x[i][i],y[i][i] # reduce 是做累计算的 # print(reduce(func,(a,b))) # func(a,b) print(lis)
''' 12. 求结果 v = (lambda :x for x in range(10)) print(v) print(v[0]) print(v[0]()) print(next(v)) print(next(v)())'''
print(v)#<generator object <genexpr> at 0x000000000289E938> # print(v[0])#TypeError: 'generator' object is not subscriptable # print(v[0]())#TypeError: 'generator' object is not subscriptable print(next(v)()) # 0 a = v.__next__() print(v.__iter__().__next__())#<function <genexpr>.<lambda> at 0x00000000028AA268> print(v.__next__)#<method-wrapper '__next__' of generator object at 0x000000000286E938> # 就这个每迭代 前面有括号的都调用了 print(next(v))#<function <genexpr>.<lambda> at 0x000000000288A2F0> print(next(v)())#4 print(next(v)())#5 print(next(v)())#6
# 和迭代器似的,
# 11. 求结果 # v = [lambda :x for x in range(10)] # print(v) # print(v[0]) # print(v[0]())
自己写
la = [] def func(i): #我自己听了老师自己写的 ,写的函数地址一样 结果对的 for i in range(10): print(end='') print(func) la.append(func) #<function func at 0x0000000000441E18> #<function func at 0x0000000000441E18> return func func(0) print(la)
老师举例
li = [] for x in range(10):# 老师说的太棒了 def func(): return x li.append(func) print(li) v = [lambda :x for x in range(10)] print(' ',v,' ',li) # 两个 分别是lambda 和函数的 10个地址 print(v[0],li[0])#<function <listcomp>.<lambda> at 0x000000000290F0D0> <function func at 0x00000000028FAA60> print(v[0](),li[0]())#9 9