Python在将值附加到嵌套列表时引发错误。我正在尝试按相同的数字对list
进行排序。如果我有一个输入([1, 2, 1, 1, 2])
,我希望将其作为[[1, 1, 1] ,[2, 2]
def find_it(seq):
seq_count = [[]]
seq_copy = seq
for i in range(0, len(seq)):
for k in seq_copy:
if seq[i] == k:
seq_count[i].append(k)
print(seq_count)
find_it([1, 2, 1, 1, 2])
必需的输出:
[[1, 1, 1] ,[2, 2]]
答案 0 :(得分:0)
执行此操作的Python方法是使用Counter
中的collections
:
from collections import Counter
seq_count = [[i]*c for i,c in Counter(seq).items()]
收益[[1, 1, 1], [2, 2]]
如果要使用显式循环,则对于seq中的每个i
,首先必须循环遍历seq_count
,检查是否存在以i
作为其第一元素的项目。如果是这样,则追加到该子列表,如果不生成新的子列表。如果您想走这条路,将seq_count
初始化为[]
而不是[[]]
会更有意义。仅当您有需要的子列表时才生成子列表。