이 코드를 도와 주시겠습니까?왜이 python 코드가 작동하지 않습니까?
s = [1, 1, 3, 3, 2, 2, 2, 2, 1, 1, 2, 2, 2]
def group(s):
lst = []
temp_lst = []
for i in s:
if len(temp_lst) == 0:
temp_lst.append(i)
continue
if temp_lst[0] == i:
temp_lst.append(i)
else:
lst.append(temp_lst)
del temp_lst[:]
temp_lst.append(i)
return lst
이 반환
[[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]
이유는 무엇입니까?
내 원하는 출력은 다음과 같습니다
[[1, 1], [3, 3], [2, 2, 2, 2], [1, 1], [2, 2, 2]]
; 'del tmp_lst [:]'는 기존 목록을 비 웁니다. 새로운 목록을 만들지 않습니다. 또한'itertools.groupby'가 도움이 될 것입니다. – jonrsharpe
['itertools.groupby'] 사용 (https://docs.python.org/3/library/itertools.html#itertools.groupby) :'[groupby의 _, g에 대해 list (g)]' –