Python Forum
# only print cities that names start "Q" or earlier
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
# only print cities that names start "Q" or earlier
#1
my question here
print cities from visited_cities list in alphbetical order using .sort()
# only print cities that names start "Q" or earlier
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
visited_cities.sort()
print(visited_cities)
new_cities=[]
for cities in visited_cities:
    if cities[0]=="A"or"B"or"C"or"D"or"E"or"F"or"G"or"H"or"I"or"J"or"K"or"L"or"M"or"N"or"O"or"P"or"Q":
        new_cities.append(cities)
print(new_cities)
But I am getting following output:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko']
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko']

But Desired output is:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']
Reply
#2
see http://python-forum.io/Thread-Multiple-e...or-keyword

also, have a look at str.startswith() method for better, more pythonic way of doing the same

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = []
for city in visited_cities:
    if city.startswith(tuple('ABCDEFGHIJKLMNOPQ')):
        new_cities.append(city)
new_cities.sort()
print(new_cities)
or even better, using list comprehension

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = [city for city in visited_cities if city.startswith(tuple('ABCDEFGHIJKLMNOPQ'))]
new_cities.sort()
print(new_cities)
in both cases, the output is
Output:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']
Sort the subset - new_cities list, not the entire visited_cities list, because it is shorter one
Reply
#3
you can use also

from string import ascii_uppercase

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = [city for city in visited_cities if city.startswith(tuple(ascii_uppercase[:17]))]
new_cities.sort()
print(new_cities)
Reply
#4
another method:

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
print('visited_cities: {}'.format(visited_cities))
new_cities=[]

for city in visited_cities:
   if city[0] < 'R':
       new_cities.append(city)
new_cities.sort()
print('new_cities: {}'.format(new_cities))
results
Output:
visited_cities: ['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko'] new_cities: ['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']
Reply
#5
This will also work:
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
visited_cities.sort()
new_cities=[]
for cities in visited_cities:
   if cities[0]<="Q":
       new_cities.append(cities)
print(new_cities)
As will :
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
for cities in visited_cities:
   if cities[0]<="Q":visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
for cities in visited_cities:
    if cities[0]<="Q":
        print(cities)
       print(cities)
Reply
#6
With a generator:

def get_till_included(iterable, start):
    found = False # set found condition to false
    for element in sorted(iterable):
        # iterates over a sorted list of strings
        # if no element fulfilled the condistion startswith, it will
        # yield the whole sorted list
        if not found:
            # yields the element if the start is not found at the beginning of the string
            yield element
            found = element.startswith(start) # look if the string starts with start
        elif found and element.startswith(start):
            # yields the element if already one was found which starts with start.
            yield element
        else:
            # stops the loop, when one element with the start was already found,
            # but the current element has not fulfilled the condition startswith
            break

# this list won't get modified
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]

generator = get_till(visited_cities, 'M')
print('generator object', generator) # does nothing, values are lazy evaluated during iteration, the print function does not iterate over something

generator = get_till(visited_cities, 'M')
print('as list', list(generator)) # as list, which is mutable

generator = get_till(visited_cities, 'M')
print('as tuple', tuple(generator)) # as immutable sequence

generator = get_till(visited_cities, 'M')
print('as set', set(generator)) # only unique elements, no order
The benefit:
  • You don't mutate the original list.
  • The generator does not define the data type of the final result
  • You can iterate over the generator

Example to iterate over the generator:
for city in get_till(visited_cities, 'M'):
    print('City:', city)
With generators you can split tasks into smaller tasks and stick them together.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Start print a text after open an async task via button Nietzsche 0 728 May-15-2023, 06:52 AM
Last Post: Nietzsche
  Print names in x-axis of a time-series values hobbyist 4 1,252 Apr-22-2023, 09:29 PM
Last Post: deanhystad
  2 versions of module installed, how to import the earlier one sveto4ka 8 4,851 Oct-22-2019, 02:51 PM
Last Post: snippsat
  What's the difference b/w assigning start=None and start=" " Madara 1 2,335 Aug-06-2018, 08:23 AM
Last Post: buran
  How to print the names of assignments if they are randomly selected Kongurinn 2 3,340 Oct-22-2017, 07:31 AM
Last Post: buran

Forum Jump:

User Panel Messages

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