【问题标题】:Looping to assign list of lists into arrays循环将列表分配到数组中
【发布时间】:2017-04-09 04:25:06
【问题描述】:

我有一个列表列表,我想将每个子列表分配给一个特定形状的形状数组。到目前为止,我有:

N=23

# read the file in lines
with open('ircforward.xyz','r') as f:
    lines = f.read().splitlines()

# Split the whole file into a list of lists 
profiles = [lines[i:i + N] for i in xrange(0, len(lines), N)]

#Convert first sublist to array skipping the first two lines    
set1 = np.genfromtxt(profiles[0],skip_header=2,usecols=[1,2,3])

有没有一种方法可以生成一堆名为“set_n”的数组,其中 n 将是一个索引变量,并且具有以下内容:

for n in range (4000):
      set_n = np.genfromtxt(profile[n], skip_header=2, usecols=[1,2,3])

【问题讨论】:

  • 与其拥有set_1set_2 等,只需构建一个数组集:sets[n] = np.genfromtxt(...)。或集合的字典。

标签: python arrays list loops numpy


【解决方案1】:

最好的解决办法是使用如下字典:

my_dict = {}

for n in range (4000):
      my_dict['set_{}'.format(n)] = np.genfromtxt(profile[n], skip_header=2, usecols=[1,2,3])

现在,您可以使用 my_dict['set_1']my_dict['set_2'] 等代替 set_1set_2

【讨论】:

  • 我还能调用数组的特定元素吗?例如,如果我想将 set1 中第二行的第一个值分配给一个变量,我可以执行类似 x = set_1[1,0] 的操作吗?
  • 你可以做x = my_dict['set_1'][1,0]
  • 是否可以通过字典作为循环进行变量赋值,类似于:for n in range (4000): 'x'.format(n) = my_dict['set_{ }'.format(n)][1,0]
  • 您不能那样创建变量,这就是我们使用字典来解决上述相同问题的原因。相反,您可以阅读 x_1 = my_dict['set_1'][1,0] 之类的一项
猜你喜欢
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
相关资源
最近更新 更多