将循环结果存储在嵌套列表中

时间:2020-09-11 19:18:34

标签: python python-3.x arraylist datatable nested-lists

我有这种插入排序算法,它生成jikeyA。我想将所有这些存储在单独的列表中。但是,当我尝试存储A时,嵌套列表会返回此值。

store_j = []
store_i = []
store_key = []
store_A = []
def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        store_j.append(j)
        store_i.append(i)
        store_key.append(key)
        store_A.append(A)
        while i >= 0 and A[i] > key:
            A[i + 1] = A[i]
            i = i - 1
            A[i + 1] = key
    print(store_i)
    print(store_j)
    print(store_key)
    print(store_A)

a = [5, 1, 3, 4, 2]
insertion_sort(a)

[0, 1, 2, 3]
[1, 2, 3, 4]
[1, 3, 4, 2]
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

我希望最后一个store_A这样输出

[[5, 1, 3, 4, 2][1, 5, 3, 4, 2][1, 3, 5, 4, 2][1, 3, 4, 5, 2][1, 2, 3, 4, 5]]

所以我最终可以用存储的值制作一张表

类似这样的东西

j | i | key|      A        |
1 | 0 | 1  |[5, 1, 3, 4, 2]|
2 | 1 | 3  |[1, 5, 3, 4, 2]|
3 | 2 | 4  |[1, 3, 5, 4, 2]|
4 | 3 | 2  |[1, 3, 4, 5, 2]|
4 | 0 | 2  |[1, 2, 3, 4, 5]|

2 个答案:

答案 0 :(得分:0)

如果我理解您的问题,那么您想要列表的所有排列。

import numpy as np
import itertools

permutations = list(itertools.permutations([5, 2, 3, 1]))
print (permutations)    # list of tuples
perm_array = np.array(permutations)
print(perm_array)       # yields 2D array

答案 1 :(得分:0)

只需在存储该数组之前对其进行复制。否则,您将保存数组A的实例,就像存储A 5次或len(A)次一样。并且A将在每次迭代中更改,并且在打印store_A时,您将在那时获得A的值。要了解这一点,您可以在print(store_A)之后添加store_A.append(A)。这会给你

[[5, 1, 3, 4, 2]]
[[1, 5, 3, 4, 2], [1, 5, 3, 4, 2]]
[[1, 3, 5, 4, 2], [1, 3, 5, 4, 2], [1, 3, 5, 4, 2]]
[[1, 3, 4, 5, 2], [1, 3, 4, 5, 2], [1, 3, 4, 5, 2], [1, 3, 4, 5, 2]]

现在,解决方法很简单,只需添加实例a即可,然后再添加存储并在循环后添加一行到append(A)以添加最后的结果。

store_j = []
store_i = []
store_key = []
store_A = []
def insertion_sort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        store_j.append(j)
        store_i.append(i)
        store_key.append(key)
        store_A.append(A.copy())
        while i >= 0 and A[i] > key:
            A[i + 1] = A[i]
            i = i - 1
            A[i + 1] = key

    store_j.append(j)
    store_i.append(i)
    store_key.append(key)
    store_A.append(A.copy())
    print(store_i)
    print(store_j)
    print(store_key)
    print(store_A)

a = [5, 1, 3, 4, 2]
insertion_sort(a)

出来就像

[0, 1, 2, 3, 0]
[1, 2, 3, 4, 4]
[1, 3, 4, 2, 2]
[[5, 1, 3, 4, 2], [1, 5, 3, 4, 2], [1, 3, 5, 4, 2], [1, 3, 4, 5, 2], [1, 2, 3, 4, 5]]

对于表格制作,您还可以添加以下代码

template='|{0:^5}|{1:^5}|{2:^5}|{3:^18}|'
print(template.format('i','j','key','A'))
for i in range (len(store_A)):
    print(template.format(f'{store_j[i]}',f'{store_i[i]}',f'{store_key[i]}',f'{store_A[i]}'))

结果将类似于

|  i  |  j  | key |        A         |
|  1  |  0  |  1  | [5, 1, 3, 4, 2]  |
|  2  |  1  |  3  | [1, 5, 3, 4, 2]  |
|  3  |  2  |  4  | [1, 3, 5, 4, 2]  |
|  4  |  3  |  2  | [1, 3, 4, 5, 2]  |
|  4  |  0  |  2  | [1, 2, 3, 4, 5]  |