Alan Wakke
Alan Wakke

Reputation: 87

How to return a list of strings from a list?

Trying to return a list of strings found in rows of lists. But the order has to be from left to right starting from the top row to lowest without returning duplicates. I'm not sure how to proceed. Would I need to make an IF statement for the letters A to Z if it matches with the list then append them to a new list?

def get_locations(lst):
    new_lst = [] # New list?
    for i in range(len(lst)):
        if 'A' lst[i] <= 'Z' or 'a' <= lst[i] <= 'z': #If strings are A to Z
            new_lst.append # Add to new list?
            return new_lst 

List example: It should return like this get_locations(lst) → ["a","B","A","z","C"]

lst1 = [['.',   '.',    'a',    'B'],
        ['.',   '.',    'a',    '.'],
        ['A',   '.',    '.',    'z'],
        ['.',   '.',    '.',    'z'],
        ['.',   '.',    'C',    'C']]

Upvotes: 2

Views: 1438

Answers (5)

sytech
sytech

Reputation: 40861

Pretty straightforward. string.ascii_letters is a good shortcut to know for all letters a-Z

import string
def get_chars(lst):
    new_list = []
    for nested_list in lst:
        for char in nested_list:
            if char not in new_list and char in string.ascii_letters:
                new_list.append(char)
    return new_list

Then:

>>> get_chars(lst1)
['a', 'B', 'A', 'z', 'C']

Upvotes: 0

Shasha99
Shasha99

Reputation: 1916

Well if you are not very much concerned about the ordering, The following statement will be powerful enough to keep lengthy methods aside:

ans = {j for i in lst for j in i if j!='.'} 

And if maintaining the order is a must to have, then you may consider using the following method:

def get_locations(lst):
    ans=[]
    for i in lst:
        for j in i:
            if (j is not '.') and (j not in ans):
                ans.append(j)
    return ans

You can also use the following generator version for your problem:

def get_locations(lst):
    ans=[]
    for i in lst:
        for j in i:
            if (j is not '.') and (j not in ans):
                ans.append(j)
                yield j

Upvotes: 0

hvwaldow
hvwaldow

Reputation: 1376

import re

def get_locations(lst):
    new_lst = [] # New list? Yes!
    # Iterate directly over "flattened" list. That involves confusing
    # nested list comprehension. Look it up, it's fun!
    for i in [e for row in lst for e in row]:
        # using regular expression gives more flexibility - just to show off :)
        if re.match('^[a-zA-Z]+$', i) and i not in new_lst:   #deal with duplicates
            new_lst.append(i) # Add to new list? yes!
    return new_lst # corrected indentation


lst1 = [['.',   '.',    'a',    'B'],
        ['.',   '.',    'a',    '.'],
        ['A',   '.',    '.',    'z'],
        ['.',   '.',    '.',    'z'],
        ['.',   '.',    'C',    'C']]

print(get_locations(lst1))

Upvotes: 0

zvone
zvone

Reputation: 19352

Let's go through the function line by line:

    new_lst = [] # New list?

Yes, it creates a new list.

    for i in range(len(lst)):

Although this is valid, there is rarely a reason to iterate through list indices in Python. You can iterate through the elements instead. Furthermore, this is a list of lists, so that should be handled as well:

    for sublist in lst:
        for character in sublist:

After that use character instead of lst[i].

        if 'A' lst[i] <= 'Z' or 'a' <= lst[i] <= 'z': #If strings are A to Z

There is a syntax error at 'A' lst[i]. Otherwise, this could work if character is actually a character. If it is a longer string, it may give unexpected results (depending on what you expect):

        if 'A' <= character <= 'Z' or 'a' <= character <= 'z':

So, an interesting character was found. Add it to the result?

            new_lst.append # Add to new list?

The function should be called:

            new_lst.append(character)

BTW, this appends the character regardless of whether it was already in new_lst or not. I gather it should only add a character once:

            if character not in new_lst:
                new_lst.append(character)

The next line returns the list, but too early:

            return new_lst

It should not be indented. It should be outside of the loops, so that the result is returned after all has been looped.

Upvotes: 3

B. Eckles
B. Eckles

Reputation: 1644

I had a ton of trouble understanding what you meant, but assuming I've figured it out, you weren't too far off:

def get_locations(lst):
    new_lst = [] # New list?
    for row in lst:
        for letter in row:
            if ('A' <= letter <= 'Z' or 'a' <= letter <= 'z') and letter not in new_lst: #If strings are A to Z
                new_lst.append(letter) # Add to new list?
    return new_lst 

Upvotes: 0

Related Questions