简体   繁体   中英

Iterating over array and slicing or making changes in Python

I'm about to pull my hair out on this. I'm not sure why the index in my array is not being implemented in the second column.

I created this array - project_information:

    project_information.append([proj_id,project_text])

When I print this out, I get the rows and columns. It contains about 40 rows.

When I iterate through it to print out the contents, everything comes out fine. I am using this:

    for i in range(0,len(project_information)):
        project_id = project_information[i][0]

        project_text = project_information[i][1]
        print(project_id)
        print (project_text)
   

The project_text column contains text, while the project_id contains integers. It prints out perfectly, and the index, changes for both project_id and project_text.

However, I need to use the project_text in a different way, and I am really struggling with this. I need to slice the text to a shorter text for reuse. To do this, I tried:

   for i in range(0,len(project_information)):
        project_id = project_information[i][0]

        project_text = project_information[i][1]
        print(project_id)
        print (project_text)
   
       if len(project_text) > 5000:
          trunc_proj_text = project_text[:1000]
       else:
          trunc_proj_text = project_text

      print (project_id)       
      print(trunc_proj_text)

The problem I'm having here is that though the project_id column is being iterated through properly, the project_text is not. What I am getting is just the text in the first row for the project_text, sliced, and repeated for as many times as the length of the array.

I have tried different ways, and also a while loop, but it is still not working.

I've also looked at these answers for reference - Slicing,indexing and iterating over 2D Numpy arrays , Efficient iteration over slice in Python , iteration over list slices , and I can't seem to see how they can be applied to my problem.

I'm not well-versed in using Numpy, so is this something that it could help with? I'm well aware this might be simple and I'm missing it because I've been working on various aspects of this project for the past weeks, so I would appreciate a bit of consideration in this.

Thanks in advance.

The problem was with the input list here, so the slicing with this code does in fact work. The code to create the input array has now been fixed. The original code to create the input list was concatenating the strings for each entry, so the project_texts for each appeared different from the end, but all had the same beginning. But viewing this on a console, it was hard to see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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