简体   繁体   English

使用循环创建 arrays (Python)

[英]Creating arrays with a loop (Python)

I am trying to create several arrays from a big array that I have.我正在尝试从我拥有的大数组中创建几个 arrays。 What I mean is:我的意思是:

data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], 
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0]]  

I want to create 10 different arrays - using the 10 data's columns - with different names.我想创建 10 个不同的 arrays - 使用 10 个数据的列 - 具有不同的名称。

data1 = [0, 0, 0, 1, 0, 0, 1, 0, 0],
data2 = [1, 0, 1, 0, 0, 0, 0, 1, 0], and so on

I found a close solution here - Also I take the example data from there - However, when I tried the solution suggested:我在这里找到了一个接近的解决方案 - 我也从那里获取示例数据 - 但是,当我尝试建议的解决方案时:

for d in xrange(0,9):
exec 'x%s = data[:,%s]' %(d,d-1)

A error message appears:出现错误消息:

exec(code_obj, self.user_global_ns, self.user_ns)

  File "", line 2, in 
    exec ('x%s = data[:,%s]') %(d,d-1)

  File "", line 1
    x%s = data[:,%s]
                 ^
SyntaxError: invalid syntax

Please, any comments will be highly appreciated.请,任何意见将不胜感激。 Regards问候

Use numpy array index:使用 numpy 数组索引:

data = [[0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], 
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 0, 0, 0, 0, 0,1], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0], 
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0]]

d = np.array(data)

d[:, 0]
#array([0, 0, 0, 1, 0, 0, 1, 0, 0])

d[:, 1]
#array([1, 0, 1, 0, 0, 0, 0, 1, 0])

etc... ETC...

d[:, 9]
#array([0, 0, 1, 1, 1, 0, 0, 0, 0])

If you must, then dictionaries are the way to go:如果必须,那么字典就是 go 的方法:

val = {i:d[:,i] for i in range(d.shape[1])}

To access the arrays:要访问 arrays:

val[0]
#array([0, 0, 0, 1, 0, 0, 1, 0, 0])

...

val[9] 
#array([0, 0, 1, 1, 1, 0, 0, 0, 0])

Use the following code (it is also more readable -- for python 3.x) if you really want to create dynamic variables:如果您真的想创建动态变量,请使用以下代码(对于 python 3.x,它也更具可读性):

for d in range(0,9):
  # exec 'x%s = data[:,%s]' %(d,d-1)
  exec(f"data{d} = {data[d]}" )
  1. I don't see the proper indentation in your for loop.我在你的 for 循环中看不到正确的缩进。

  2. I suggest you don't use %s for the second argument (string) but rather %d (number) since you need a number to do the indexing of your array.我建议您不要将 %s 用于第二个参数(字符串),而应使用 %d(数字),因为您需要一个数字来对数组进行索引。

Either use numpy array as shown by scott boston above or use dictionary like this:使用 numpy 数组,如上面的 scott boston 所示,或者使用这样的字典:

a = {}

for i in range(0,9):
    a[i] = data[i][:]

Output: Output:

{0: [0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
 1: [0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
 2: [0, 1, 1, 0, 0, 0, 0, 0, 0, 1],...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM