如果我有一个列表,如何从中创建一个重复列表列表? 例如,如果我有列表
L = [1,2,1,3,4,2,1,4]
我希望输出为
L1 = [[1,1,1], [2,2], [3], [4,4]]
答案 0 :(得分:2)
作为collections.Counter
答案的替代方案,您可以使用itertools.groupby
:
import itertools
L = [1,2,1,3,4,2,1,4]
grouped = [list(group) for key, group in itertools.groupby(sorted(L))]
print(grouped) # -> [[1, 1, 1], [2, 2], [3], [4, 4]]
答案 1 :(得分:1)
必须有大约一百种方法。这是一个。如果你想要更多,那么这真的是一个Python问题,在你的问题中添加Python标签。
// common.js because you ll commonly use them
import Element from './Element.component';
import Element2 from './Element.component2'; // x50 ?
/* ... */
export { Element, Element2 /* ... */ };
// in someOtherFile.js
import * as Elements from './common';
/*
now you are able to use these common elements as
<Elements.Element />
<Elements.Element2 />
...
*/
答案 2 :(得分:0)
@ Bill_Bell答案的变体。
>>> L = [1, 2, 1, 3, 4, 2, 1, 4]
>>> from collections import Counter
>>> counts = Counter(L)
>>> counts
Counter({1: 3, 2: 2, 4: 2, 3: 1})
>>> L2 = [[a]*b for (a,b) in counts.items()]
>>> L2
[[1, 1, 1], [2, 2], [3], [4, 4]]