Home > Software design >  Splitting a list a specific amount of times
Splitting a list a specific amount of times

Time:04-19

I have an input file containing names, last names and GPA's of students. I'm having a bit of trouble as this is the first time I'm working with splitting text files. I want to split the text file, store it in the Temp list, then put the first and last names in Names and GPA's in Scores. The code below splits the file and puts it in Temp but unfortunately it is splitting it by name, last name and GPA.Is there a way to have it split by names and GPA and not names last names and GPA? This is my output: enter image description here

This is what I came up with so far:

def main():
try:
    
    inputFile=open("input.txt", "r")
    
    outputFile=open("output.txt", "w")
    
    Names=[]
    Scores=[]
    
    Temp=[]
    for i in inputFile:
        splitlist=i.split()
        Temp.append(splitlist)
        
    print(Temp)

except:
    print(" ")

main()

CodePudding user response:

You can use rsplit and specify a maximum number of splits

 splitlist = i.rsplit(maxsplit=1)

Except for splitting from the right, rsplit() behaves like split()

CodePudding user response:

So, basically, there are 2 ways to achieve your desired result

1. Splitting at the last occurence (easy, recommended method)

In Python, strings can be split in two ways:

  1. "Normal" splitting (str#split)
  2. "Reverse" splitting (str#rsplit), which is like split, but it from the end of the string

Therefore, you can do something like this:

splitlist = i.rsplit(maxsplit=1)

2. Overengineered method (not recommended, but overengineered)

You can reverse your string, use split with a maxsplit of 1, reverse the resulting list AND reverse every entry in the list

So:

splitlist = [j[::-1] for j in i[::-1].split(maxsplit=1)][::-1]

;)

  • Related