简体   繁体   English

如何使用for循环将字符串附加到数组中的特定位置

[英]How to append strings to a specific position in an array with for loop

I am new to python and Linux.我是 python 和 Linux 的新手。 I found a problem while trying append strings to a specific position in an array with a for loop.我在尝试使用 for 循环将字符串附加到数组中的特定位置时发现了一个问题。
This is simplied description of my work.这是对我的工作的简单描述。

This is my input file1:这是我的输入文件 1:
a,b,c,d,e,f a,b,c,d,e,f

Input file2:输入文件2:
name1,a,b,d,e名称1,a,b,d,e
name2,b,e,f名称2,b,e,f

I would like to get the output file that the same letter will be in the same column as shown below:我想获得相同字母将在同一列中的输出文件,如下所示:

  a,b,c,d,e,f
  name1,a,b,0,d,e,0
  name2,0,b,0,0,e,f

I search for Linux scripts but so far I could not found the suitable one.我搜索了 Linux 脚本,但到目前为止我找不到合适的脚本。 Then, I tried with NumPy array in python but there is only np.insert or np.append function but they seem to not appropriate for my situation.然后,我尝试在 python 中使用 NumPy 数组,但只有 np.insert 或 np.append 函数,但它们似乎不适合我的情况。
Following is the python script that I processed以下是我处理的python脚本

    import numpy as np
    header = np.loadtxt("file1.txt", dtype= str, delimiter=',')
    lines = np.loadtxt("file2.txt", dtype= str, delimiter=',')
    ARG = np.empty([2,7], dtype=str)
    for x, line in enumerate(lines):
       for i in line:
          for y, j in enumerate(header):
             if i == j:
               np.insert(ARG, y, i, axis=x)
               print(ARG)
             else:
               np.insert(ARG, y, 0, axis=x)
    np.savetxt('test.csv', ARG, delimiter=',')

The output shows an error like IndexError: index 3 is out of bounds for axis 0 with size 2, and the added strings were not at the correct position in the array.输出显示错误,如 IndexError: index 3 is out of bounds for axis 0 with size 2,并且添加的字符串不在数组中的正确位置。 Would you mind giving me some suggestions?你介意给我一些建议吗?
Thank you.谢谢你。

Try this.尝试这个。 insert function does the work here: insert函数在这里完成工作:

my_list1 = ['name1','a','b','d','e']
my_list2 = ['name2','b','e','f']

my_list1.insert(3,0)
my_list1.insert(7,0)

my_list2.insert(1,0)
my_list2.insert(4,0)
my_list2.insert(5,0)
print(my_list1)
print(my_list2)

output:输出:

['name1', 'a', 'b', 0, 'd', 'e', 0]
['name2', 0, 'b', 'e', 0, 0, 'f']

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

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