Home > Software engineering >  How do I split and sort strings in a list using for loops in Python
How do I split and sort strings in a list using for loops in Python

Time:03-29

Trying to read a file then store it in a list but not getting the desired output:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    #line = line.rstrip()
    words = line.split()
        if words not in lst:
            lst.append(words)
            
lst.sort()
print(lst)

My Output:

[['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'], ['Who', 'is', 'already', 'sick', 'and', 'pale', 'with', 'grief']]

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

CodePudding user response:

All you have to do is loop through all of the words in the sentence, then check if they are already in the list, then append them.

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    #line = line.rstrip()
    words = line.split()
    for word in words:
       if word not in lst:
            lst.append(word)
            
lst.sort()
print(lst)
  • Related