【问题标题】:python 3 How to store result in array every repetition in a loop in the same index [duplicate]python 3如何在同一索引中的循环中每次重复将结果存储在数组中[重复]
【发布时间】:2018-08-16 12:28:33
【问题描述】:

我正在使用 python-3.x,我有两个循环。第一个运行 3 次,第二个生成解决方案(循环运行 2 次)。

我想做的是:从第二个循环中收集最佳解决方案并将其附加到数组或列表中。下一次运行,即第一个循环,将再次运行第二个循环,它将从第二个循环中收集最佳解决方案并将其附加到相同的数组或列表中。这样,每个循环运行我将有两个解决方案,总共有六个解决方案。

问题是:我想在下次运行时将“最佳解决方案”附加到同一索引。

在我的例子中,数组的大小为 6 个索引,但我希望它的大小为 3,其中每个索引将包含两个值(最佳解决方案)。

运行 1:数组内的结果:index 0“第一个最佳解决方案。” index 1 "次优方案。"

运行 2:数组内的结果:index 0“第一最佳解决方案”和“第一最佳解决方案”。

index 1“第二好的解决方案”和“第二好的解决方案。”

如果你看一下代码,结果应该很清楚,你会看到我想要做什么。

您可以提供任何建议或帮助,我们将不胜感激。

import matplotlib.pyplot as plt
import math
import random
import numpy as np
import pylab      
from numpy import median
import os
import subprocess as sp

run = 3
best_solutions = [np.empty(0)]
del best_solutions[0]

for i in range (run):
    lower = 300
    upper  = 500
    number_of_solutions = 50
    generate_solutions = 2 
    ####sub list 
solution = []
for ii in range (generate_solutions):     
    list_of_solutions = np.random.uniform(lower, upper, number_of_solutions)
#### append to the sub_list
    solution.append(min(list_of_solutions))
    lower = lower - 30.4323434
    upper  = upper - 90.634555
#### append the sub_list to best_solutions

    best_solutions.append(solution)

为了更清楚...

如果 (i) = 0 如果 (ii) = 0,则此循环中的 min(solution) 将存储在索引 0 的 best_solutions 中

如果 (ii) = 1,则此循环中的 min(solution) 将存储在索引 1 的 best_solutions 中

如果 (ii) = 2,则此循环中的 min(solution) 将存储在索引 2 的 best_solutions 中,依此类推......

第二次运行:如果 (i) = 1 如果 (ii) = 0,则此循环中的 min(solution) 将存储在索引 0 的 best_solutions 中

如果 (ii) = 1,则此循环中的 min(solution) 将存储在索引 1 的 best_solutions 中

如果 (ii) = 2,则此循环中的 min(solution) 将存储在索引 2 的 best_solutions 中,依此类推......

我希望这能阐明我想要做什么! 我尝试按索引存储它们:

best_solutions[ii].append(solution[ii])

但它给了我一个错误:IndexError: **list index out of range**

我的结果应该是这样的:

 best_solutions
  Final result                   solution
 array or list                  array or list

Index                     Index
       ++++++++                 ++++++++      
       +  1   +                 +  1   +
  0    +  1   +            0    +  2   +
       +  1   +                 +  3   +
       ++++++++                 ++++++++
       +  2   +                 +  1   +
  1    +  2   +            1    +  2   +
       +  2   +                 +  3   +
       ++++++++                 ++++++++
       +  3   +                 +  1   +
  2    +  3   +            2    +  2   +
       +  3   +                 +  3   +
       ++++++++                 ++++++++

【问题讨论】:

  • 缩进有问题吗?
  • 抱歉,您所说的“缩进”是什么意思
  • @azeez... 我已经删除了您提供的不相关的代码,并将脚本制作成它应该的样子。该代码带有一些内联 cmets,以帮助您更好地理解某些内容。享受吧!

标签: arrays python-3.x list append


【解决方案1】:

根据您的“它应该如何工作”,这是您正在寻找的内容。我使用了具有浮动值的示例数组,以便能够向您显示每行中的位置以及脚本末尾的值的排序,否则如果我使用整数是不可能的。

import numpy as np

# test data
solution       = np.array([[1.1, 2.3, 3.2], [2.1, 1.2, 3.3], [1.3, 3.1, 2.2]], dtype = float)
best_solutions = np.zeros((3,3), dtype = float)

print solution

print best_solutions

shape_solutions = solution.shape
shape_best_solutions = best_solutions.shape

run, depth = shape_solutions

low   = 1.2
upper = 1.4

positions_1 = 0
positions_2 = 0
positions_3 = 0

for i in range(1, run+1):
    print 'check row : %s' % i
    for j in range(1, depth+1):
        value = solution[i-1][j-1]
        print 'row/depth : %s-%s - Got value "%s".' % (i,j, value)

        if value in [1.1, 1.2, 1.3]:
            print 'This is value : %s' % value
            best_solutions[0][positions_1] = value
            positions_1 += 1

            # this code is just here to show low and upper sorting creteria for your lower = 300 and upper = 500
            if low < value < upper:
                print "I've got a value ""%s"" between two limits ""%s-%s""..yeah!" % (value, low, upper)

        elif value in [2.1, 2.2, 2.3]:
            print 'This is value : %s' % value
            best_solutions[1][positions_2] = value
            positions_2 += 1

        elif value in [3.1, 3.2, 3.3]:
            print 'This is value : %s' % value
            best_solutions[2][positions_3] = value
            positions_3 += 1

print best_solutions

best_row, best_depth = shape_best_solutions

#sort values in each row/run
for i in range(best_row):
    best_solutions[i].sort()

print best_solutions

从我这边来看,标准输出如下所示:

[[1.1 2.3 3.2]
 [2.1 1.2 3.3]
 [1.3 3.1 2.2]]

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

check row : 1
row/depth : 1-1 - Got value "1.1".
This is value : 1.1
row/depth : 1-2 - Got value "2.3".
This is value : 2.3
row/depth : 1-3 - Got value "3.2".
This is value : 3.2
check row : 2
row/depth : 2-1 - Got value "2.1".
This is value : 2.1
row/depth : 2-2 - Got value "1.2".
This is value : 1.2
row/depth : 2-3 - Got value "3.3".
This is value : 3.3
check row : 3
row/depth : 3-1 - Got value "1.3".
This is value : 1.3
I've got a value 1.3 between two limits 1.2-1.4..yeah!
row/depth : 3-2 - Got value "3.1".
This is value : 3.1
row/depth : 3-3 - Got value "2.2".
This is value : 2.2

[[1.1 1.2 1.3]
 [2.3 2.1 2.2]
 [3.2 3.3 3.1]]

[[1.1 1.2 1.3]
 [2.1 2.2 2.3]
 [3.1 3.2 3.3]]

你想要这个吗?

[[[1.1],
  [ 1.2],
  [ 1.3]],
 [[2.1],
  [2.2],
  [2.3]],
 [[3.1],
  [3.2],
  [3.3]]]

灵活性:

import numpy as np

# test data
solution       = np.array([[1.1, 2.3, 3.2, 4.1], [2.1, 1.2, 3.3, 4.2], [1.3, 3.1, 2.2, 2.4]], dtype = float)
#solution       = np.array([[[1.1, 4.1], [2.3, 4.2], [3.2, 4.3]], [[2.1, 4.4], [1.2, 4.5], [3.3, 4.6]], [[1.3, 4.7],[3.1, 4.8], [2.2, 4.9]]], dtype = float)

sort_filters = ((1.0, 1.4), (2.0, 2.5), (3.0, 3.4), (4.0, 4.4))

#  all values might be within range of one filter set. Better to set column length to max.
column_width    = solution.size
solutions_shape = solution.shape

print 'solutions_shape             : %s' % str(solutions_shape)
print 'best solutions column_width : %s' % (column_width)

# Select bast solutions array based on solutions array shape.
array_type = 0

if  len(solutions_shape) == 3:   # selects if it has 3rd dimension.
    print 'got 3d array', solution

    rows, subrows, columns = solutions_shape
    array_type           = 3
    # the number of rows are based on filter size
    best_solutions       = np.zeros((len(sort_filters), subrows, columns), dtype = float)

else:
    print 'got 2d array\n', solution

    rows, columns    = solutions_shape
    array_type     = 2
    # the number of rows are based on number of filter sets.
    best_solutions = np.zeros((len(sort_filters), column_width), dtype = float)
    print best_solutions



shape_best_solutions = best_solutions.shape

# location for best_solutions where next value should be stored.
next_position = {}

if array_type == 2:

    for i in range(1, rows+1):
#        print 'check row : %s' % i

        for j in range(1, columns+1):
            value = solution[i-1][j-1]
#            print '\nrow/columns      : %s-%s - Got value "%s".' % (i,j, value)

            filter_number = 0

            for selection_keys in sort_filters:
                x, y = selection_keys
#                print ' filter_no....   : %s - values : (%s, %s)' % (filter_number, x, y)
                row_position = filter_number
#                print ' next_position   : %s\n' % (next_position)

                # create row entry for position storage based on sort_filter sets
                if next_position.has_key(row_position) != True:
                    next_position[row_position] = 0
#                    print ' entry no. added : %s' % row_position

                if x < value < y:
                    #print 'This is value : %s' % value

                    column_position = next_position[row_position]
#                    print ' best sol.col.no : %s.' % column_position

                    best_solutions[row_position][column_position]= value
                    next_position[row_position] = column_position + 1
#                    print best_solutions
                else:
                    # print "no fit"
                    pass
                filter_number += 1


print best_solutions, next_position

# removes excess columns with zeros
last_column_with_values = next_position.values()

last_column_with_values.sort()

remove_column_from = last_column_with_values.pop()

best_row, best_columns = shape_best_solutions

best_solutions = np.delete(best_solutions, np.s_[remove_column_from:best_columns], axis=1)

print best_solutions

#sort values in each row/run
for i in range(best_row):
    best_solutions[i].sort()

print best_solutions

应该打印出来:

solutions_shape             : (3L, 4L)
best solutions column_width : 12
got 2d array
[[1.1 2.3 3.2 4.1]
 [2.1 1.2 3.3 4.2]
 [1.3 3.1 2.2 2.4]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[1.1 1.2 1.3 0.  0.  0.  0.  0.  0.  0.  0.  0. ]
 [2.3 2.1 2.2 2.4 0.  0.  0.  0.  0.  0.  0.  0. ]
 [3.2 3.3 3.1 0.  0.  0.  0.  0.  0.  0.  0.  0. ]
 [4.1 4.2 0.  0.  0.  0.  0.  0.  0.  0.  0.  0. ]] {0: 3, 1: 4, 2: 3, 3: 2}
[[1.1 1.2 1.3 0. ]
 [2.3 2.1 2.2 2.4]
 [3.2 3.3 3.1 0. ]
 [4.1 4.2 0.  0. ]]
[[0.  1.1 1.2 1.3]
 [2.1 2.2 2.3 2.4]
 [0.  3.1 3.2 3.3]
 [0.  0.  4.1 4.2]]

【讨论】:

  • 感谢您付出的努力和时间,但这不是我想要的
  • .. 解释一下出了什么问题,因为如果它只是一个 x/y 转换......那将是你用 pandas 处理的东西。
  • 很抱歉缺少解释,但列表的长度取决于 generate_solutions 所以它可以是 1 或超过 100,它们都是变量值(run 和 generate_solutions )。例如,如果我有 100 个运行和 10 个 generate_solutions,结果将是列表或数组:大小为 10,其中每个索引将包含 100 个解决方案
  • 我明白了......那么你应该做的是run, depth, column = shape_solutions 而不是run, depth = shape_solutions 然后在你的第一个for循环中实现那个3d“列”维度。索引“行”和子索引“子行”变得灵活,因为我问的是数组的维度/形状。使用我为您提供的代码,您可以玩,因为您发布的代码......除了创建带有附加值的变量三遍之外,根本没有做任何事情......
  • 一旦您根据我的上述评论发布自我回答,或者如果您再次遇到错误,请通过在其下方进行编辑评论和代码,在您的问题中发布更新的“尝试”。那我再看一遍。我整天在我的电脑后面编码,如果我愿意为你编码,我会阻止你的学习曲线进步;-)
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 2013-07-18
相关资源
最近更新 更多