1

I am working on cut up method in python. Where I am breaking the text of text file in columns. I want to change the order of the elements, meaning if text is sbreaking into column A, B and C, I want to now display the text in column A, C and B. My program is as following

import sys
def first(aList):
    for row in colList:
        for item in row:
            print(item, end="        ")
        print()




ncolumns = int(input("Enter Number of Columns:"))
file = open("alice.txt", "r")

rowL= []
colList= []

print(" ")
print(" ")
print("++++++++++++++++++++++++++++++++++++++")

while True:
    line = file.readline()
    if not line:
        break

    numElements = len(line.rstrip())
    _block= numElements//ncolumns
    block = _block
    start=0
    rowL =[]

    for count in range(0,(ncolumns)):
        columnChars = ""
        for index in range(start,block):
          columnChars += line[index]  

        rowL.append(columnChars)

        start = block
        block = block + _block

        if (block < numElements):
            if((block + _block)>numElements):
                block = numElements
    colList.append(rowL)
file.close()
first(colList)  

2 Answers2

0

Just create a new list indexing the elements from the old list.

That is to say,

old_list = [1, 2, 3]
new_list = [old_list[0], old_list[2], old_list[1]]

which would give new_list as [0, 3, 2].

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

You use slice assignment here.

lst= [0,1,2]
lst[1:]=lst[1:][::-1]
print(lst)
# [0, 2, 1]

Take a look at How slicing as assignment works if you don't get it.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58