Python中的列表按相同元素分割
修改于2019年3月11日
方法之一:
方法之二: 用生成器。请看。Python列表元素分组 - 通过python学会编程 - 专栏
方法之三:
【Python中的列表按相同元素分割】
■网友a = g = ].append(y) if x == y else g.append() for x, y in zip(a, a)]print(g)# , , , , , , ]
■网友x = x = ]reduce(lambda x,y:x++y] if y in x else x+,map(lambda x:,x))
■网友
看了前面的几个答案,都不太符合我的思路。我能想到的比较清晰的一种方案是:import functoolsfrom typing import Listdef split_list(m: List], elm: int) -\u0026gt; List]: if len(m) and m != elm: m.append() m.append(elm) return mfunctools.reduce(split_list, , ])# Result: , , , , , , ]要更“古怪”一点,就这样:original = split_list = (lambda m=], cnt=0: m if cnt == len(original) else ( split_list(m+]], cnt+1) if len(m) and m != original else split_list(m++]], cnt+1)))split_list()# Result: , , , , , , ]当然,第一种方式是最简洁,最 Pythonic 的。
■网友lst = def return_cut_list(input): rt = n = 0 for i in range(len(lst)-1): if lst != lst: rt.append(lst) n = i+1 rt.append(lst) return rtprint return_cut_list(lst) output:, , , , , , ]
■网友
1. 根据python语言特性来思考问题2. pythonic很重要
推荐阅读
- 鄂温克冬季马赛-30℃极寒开赛:寒冬中的火热派对
- 大雪@大雪腌肉 适当进补 今日大雪
- |电商事业中的“闪光少年”
- 怎样成为一名合格的Python程序员?
- python 爬虫,咋获得输入验证码之后的搜索结果
- hadoop中的mapreduce链接(mapreduce chaining)怎样避免中间文件的产生
- python的html5lib这个库咋使用啊我在网上也没有找到相关文档
- 经观汽车|日系车企中的“异类”?东风日产将导入e-POWER技术大干增程式混动 | 经观汽车
- 中年|这些东西,比你想象中的还要大得多!
- 零基础入门学习啥语言好
