【问题标题】:how to store a list in a single array index如何将列表存储在单个数组索引中
【发布时间】:2017-07-05 12:08:19
【问题描述】:

如何在单个数组索引中存储完整的列表?

ip[x]=[1,2,3,1,2,3,3,2,1,1]

def fitness(c)
      ..
      ..
      return

for x in range(0, 100):
    print 'chromosome%d'%(x+1)
    c=[randint(1,3) for y in range(10)]
    fitness(c)
    ip[x]=c

【问题讨论】:

  • 正是这样:Python 是动态类型的,因此您可以将 anything 存储在数组中。
  • 或任何其他方式来实现它,以便我能够专门访问每个列表
  • 有人能尽快回答吗?

标签: arrays python-2.7 list indexing


【解决方案1】:

我真的不明白你想要什么。正如 Willem 在 cmets 中告诉您的那样,您可以将任何内容存储在数组中。您是否正在尝试做类似的事情?

import numpy as np

L = []

for x in range(11):
    c=[np.random.randint(1,4) for y in range(10)]
    L.append(c)

array = np.array(L)

print array

结果如下:

[[1 2 1 1 2 1 2 3 1 2]
 [2 1 2 3 1 3 1 3 3 2]
 [3 3 2 3 1 2 2 1 2 3]
 [1 3 1 1 1 1 1 2 2 1]
 [2 2 2 2 3 1 2 1 3 2]
 [1 3 1 1 1 2 3 1 3 3]
 [1 3 3 3 2 3 3 2 2 2]
 [3 2 1 3 2 3 1 1 1 3]
 [3 1 1 2 1 1 1 2 2 2]
 [2 3 2 2 3 2 3 2 1 3]
 [1 2 2 3 3 1 3 3 1 1]]

编辑:或者类似的东西?

import numpy as np

L1 = []

L2 = []


for j in range(3):
    for i in range(3):
        c = [np.random.randint(1,4) for y in range(10)]
        L2.append(c)
    L1.append(L2)
    L2 = []

print np.array(L1)

结果如下:

[[[1 3 3 2 1 3 2 1 1 3]
  [3 2 2 1 1 1 2 3 3 1]
  [1 2 3 3 1 1 3 1 1 2]]

 [[3 1 1 1 2 2 2 1 2 1]
  [1 3 3 3 1 1 1 1 1 2]
  [2 3 1 1 1 2 1 1 1 3]]

 [[1 3 3 1 3 2 3 1 2 3]
  [3 3 2 3 3 3 1 2 3 2]
  [2 3 3 2 2 1 3 1 1 3]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多