# python创建list - python打印list

## 将列表元素的连续重复包装成子列表 (4)

``````% ?- pack([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X).
% X = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]].
``````

``````pack([], []).
pack([X], [[X]]).
pack(Liste, Ergebnis):-
Liste = [H, T|TS],
H \= T,
pack([T|TS], Ergebnis1),
append([[H]], Ergebnis1, Ergebnis).
pack([H, H|HS], Ergebnis):-
pack([H|HS], Ergebnis1),
append([H|HS], Ergebnis1, Ergebnis).
``````

``````pack([H, H|HS], [[H|TFR]|TR]):-
pack([H|HS], [TFR|TR]).
``````

``````pack([H, T|TS], [[H]|TR]):-
H \= T,
pack([T|TS], TR).
``````

``````partition( []      , []    , []     ) .
partition( [X]     , [X]   , []     ) .
partition( [X,Y|Z] , [X]   , [Y|Z]  ) :- X \= Y .
partition( [X,Y|Z] , [X|P] , S      ) :- X  = Y , partition([Y|Z],P,S) .
``````

``````pack([],[]) .               % packing an empty list yields the empty list
pack([X|Xs],[P,Ps]) :-      % packing a non-empty list consists of
partition([X|Xs],P,T) ,   % - partitioning it into its prefix and suffix, and
pack(T,Ps)                % - packing the suffix
.                         %
``````

``````pack(L, LP) :-                  % pack/2
phrase(pack(L), LP).

pack([]) --> [].                % pack//1
pack([X]) --> [[X]].
pack([H, H1 | T]) -->
{H \= H1},
[[H]],
pack([H1 | T]).
pack([H, H | T]) -->
pack([H | T], [H]).

pack([H, H | T], P) -->         % pack//2
pack([H | T], [H|P]).
pack([H, H1 | T], P) -->
{H \= H1},
[[H | P]],
pack([H1 | T]).
pack([H, H], P) -->
[[H,H|P]].
``````

``````?- splitlistIfAdj(dif,[a,a,a,a,b,c,c,a,a,d,e,e,e,e],Lists).
Lists = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]]. % succeeds deterministically
``````

``````?- splitlistIfAdj(dif,[A,B,C],Lists).
A = B,    B = C,    Lists = [[C, C, C]]    ;
A = B,    dif(B,C), Lists = [[B, B], [C]]  ;
dif(A,C), B = C,    Lists = [[A], [C, C]]  ;
dif(A,B), dif(B,C), Lists = [[A], [B], [C]].
``````