Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
startswith() function
#1
hi, im new to coding hence i have a rather simple problem!
im trying to sort a list of cities, so that for cities that start with a letter greater than Q, the city name is removed from the list.
My code runs but i dont seem to get the correct output.
How can i specify startswith greater than Q?
many thanks for your help.


visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
sorted_cities=sorted(visited_cities)
print(sorted_cities)

for x in sorted_cities:
    if x>="Q":
        sorted_cities.remove(x)
    else:
        pass
print(sorted_cities)
Reply
#2
You're trying to compare the whole word (x) to one letter. You want to look at the first letter of the word (strings support the [] operator).
Reply
#3
Small change:
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
unique_visited_cities = set(visited_cities)
sorted_cities = sorted(unique_visited_cities)
print('All sorted cities:',sorted_cities)

cities_till_q = []
for city in sorted_cities:
    if city[0].lower() > 'q':
       break
    cities_till_q.append(city)

print('Sorted cities till q (inclusive):', cities_till_q)
The function set comes from set theory. A set has only unordered unique elements.
Sets are very useful:
set(['A', 'B', 'C']) & set(['X', 'Y', 'A', 'Z', 'U'])
We get only elements, which are in both sets.
Output:
{'A'}
Instead of running the loop on module level, make a function to be more flexible.
def get_cities(unsorted_cities, letter)
    ret = []
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        ret.append(city)
    return ret
Next iteration should be a docstring.
def get_cities(unsorted_cities, letter)
    """
    Returns a new list of unsorted cities.
    Cities which letter is bigger than the given letter
    are filtered.
    """
    ret = []
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        ret.append(city)
    return ret
Instead of creating inside the function a new list, you can also make a generator.
Lesser code, only one different statement and more flexibility.
def get_cities(unsorted_cities, letter):
    """
    Iterates over unsorted cities and
    yield cities, where the first letter
    is bigger than letter.
    """
    for city in unsorted_cities:
        if city[0].lower() > letter.lower():
           continue
        yield city


# you have to call the function to get the generator (lazy)
# Then you need to consume the generator.
# You can use the generator in a for-loop
# or you use functions where the constructor
# iterates over the argument

list(get_cities(sorted_cities, 'q'))
list(get_cities(sorted_cities, 'h'))
list(get_cities(unsorted_cities, 'h'))
list(get_cities(unique_visited_cities, 'h'))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
Thats great thank you so much for explaining all of this!
Never heard of the set function so thank you for introducing it
Reply
#5
I found the set function very late. The story behind was: I needed a function to get rid of all duplicates, which were in another list. The task was to compare if a directory has changed files which differs from original and then it was synchronizing them. First I had a made a very ugly function to solve this task. The use of set was reducing the complexity in my code.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020