我很难迭代地添加到列表中。
以下是MWE:
# Given a nested list of values, or sets sets = [[1, 2, 3], [1, 2, 4], [1, 2, 5]] # add a value to each sublist giving the number of that set in the list. n_sets = len(sets) for s in range(n_sets): (sets[s]).insert(0, s) # Now repeat those sets reps times reps = 4 expanded_sets = [item for item in sets for i in range(reps)] # then assign a repetition number to each occurance of a set. rep_list = list(range(reps)) * n_sets for i in range(n_sets * reps): (expanded_sets[i]).insert(0, rep_list[i]) expanded_sets
返回
[[3, 2, 1, 0, 0, 1, 2, 3], [3, 2, 1, 0, 0, 1, 2, 3], [3, 2, 1, 0, 0, 1, 2, 3], [3, 2, 1, 0, 0, 1, 2, 3], [3, 2, 1, 0, 1, 1, 2, 4], [3, 2, 1, 0, 1, 1, 2, 4], [3, 2, 1, 0, 1, 1, 2, 4], [3, 2, 1, 0, 1, 1, 2, 4], [3, 2, 1, 0, 2, 1, 2, 5], [3, 2, 1, 0, 2, 1, 2, 5], [3, 2, 1, 0, 2, 1, 2, 5], [3, 2, 1, 0, 2, 1, 2, 5]]
而不是期望的
[[0, 0, 1, 2, 3], [1, 0, 1, 2, 3], [2, 0, 1, 2, 3], [3, 0, 1, 2, 3], [0, 1, 1, 2, 4], [1, 1, 1, 2, 4], [2, 1, 1, 2, 4], [3, 1, 1, 2, 4], [0, 2, 1, 2, 5], [1, 2, 1, 2, 5], [2, 2, 1, 2, 5], [3, 2, 1, 2, 5]]
为了好玩,第一个循环返回一个预期值sets
[[0, 1, 2, 3], [1, 1, 2, 4], [2, 1, 2, 5]]
但在第二个循环sets
变为
[[3, 2, 1, 0, 0, 1, 2, 3], [3, 2, 1, 0, 1, 1, 2, 4], [3, 2, 1, 0, 2, 1, 2, 5]]
我怀疑这个问题与副本和参考文献有关。我尝试过在不同的地方添加.copy()
和切片,但对于索引的子列表,我还没有找到一个有效的组合。我正在运行Python 3.10.6。
感谢您的观看!