Python中的列表按相同元素分割

修改于2019年3月11日
Python中的列表按相同元素分割

方法之一:
Python中的列表按相同元素分割



方法之二: 用生成器。请看。Python列表元素分组 - 通过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很重要Python中的列表按相同元素分割


    推荐阅读