Home > Enterprise >  How do i use string index to single out first letters in a multiple element list/or tuple
How do i use string index to single out first letters in a multiple element list/or tuple

Time:10-21

How would I create a function essentially to single out only the a specific character for each element of the provided string logic I'm looking for:

ex. in a list of elements like:

countries_and_capitals = (
    ['Afghanistan', 'Kabul'], ['Albania', 'Tirana (Tirane)'], ['Algeria', 'Algiers'], ['Andorra', 'Andorra la Vella'],
    ['Angola', 'Luanda'], ['Antigua and Barbuda', "Saint John's"], ['Argentina', 'Buenos Aires'],
    ['Armenia', 'Yerevan'])

How could i create a logic to only display the elements that have the same First Letter for both Capital And Country ex. Algeria, Algiers.

CodePudding user response:

If only use the First letter to determine matching, it'll probably be too loose and select some more as the results. For example: South Korea - Seoul; or Belgium to Brussels. Not sure this is desirable? even it meets the initial requirement.

So to make this function more adaptable - this just makes the matching criteria as one character as default, but can be changed to select more characters if that's desirable later.

def find_same_name(lst, matching=1):
    '''
    find all matching capitals with Coutries, minimum matching is One char.
    '''

    # list comprehension

    return [sub  for sub in lst      
                 if sub[0][:matching] == sub[1][:matching]] # can determine matched req. 

  

Running it:

print(find_same_name(countries_and_capitals))

Output:

[['Algeria', 'Algiers'], ['Andorra', 'Andorra la Vella']]

CodePudding user response:

Try this:

new_list = []

for sublist in countries_and_capitals:

    if sublist[0][0] == sublist[1][0]:

        new_list.append(sublist)

And you'll get:

new_list

[['Algeria', 'Algiers'], ['Andorra', 'Andorra la Vella']]

CodePudding user response:

You can index the first character in a string using [] brackets

string = "ABC"

print(string[0]) # Will print first character in the string
  • Related