简体   繁体   中英

Quicker solution to the problem with loops and dictionaries

I have solved one issue recentely and I know for sure that there must be quicker solution to the problem. I am just learning and I want to write efficient code so it would be helpful if you could suggest me anything.

I want this output (which I got):

Jozefína likes to go to here: Amsterdam ,Liverpool ,London.
Marek likes to go to here: Košice.
Jozef likes to go to here: Lisabon ,Vancouver.

PS: names of people and cities are totaly random so you can change it

And my code for this problem is :

favourite_places = {
    "Jozefína": ["Amsterdam", "Liverpool", "London"],
    "Marek": ["Košice"],
    "Jozef": ["Lisabon", "Vancouver"]
}


for name in favourite_places:
    line = ""
    for place in favourite_places[name]:
        if len(favourite_places[name]) == 1:
            line = place
        else:
            line += place + " ,"
    if line[-1] == ",":
        line = line[0:-2]
    print(f"{name} likes to go to here: {line}.")

In the end I want to have one sentence with name of the person and places that he or she likes to go to (devided by the comma).

I hope I described the problem correctely. I just want to optimalize my code. I will be grateful for any suggestions.

What you are missing is a join and items functions. join joins all items of iterable with specified delimiter. If there is only 1 item, no delimiter will be added. It is generally considered a bad practise to concatenate strings with + or += . Strings are immutable and thus each concatenation produces a new string, that has to have memory allocated for it. To avoid this, you could first collect all parts of strings into list (which you already have as an input) and then join them.

items() returns tuples of (key, value) of dictionary.

favourite_places = {
    "Jozefína": ["Amsterdam", "Liverpool", "London"],
    "Marek": ["Košice"],
    "Jozef": ["Lisabon", "Vancouver"]
}


for name, places in favourite_places.items():
    print(f"{name} likes to go to here: {', '.join(places)}.")

The simplest way I can think of to accomplish this is like this:

for name, places in favourite_places.items():
  print(f'{name} likes to go here: {", ".join(places)}.')

The .items() returns a list of (key, value) tuples from the dictionary, which are deconstructed into name and places, then the ", ".join(places) will return a string that separates each element in the list of places with a comma, and will automatically leave it out if there is only a single element.

Try using replace

for name, places in favourite_places.items():  
    print(name + " likes to go to here: " + str(places).replace('[', '').replace("'", "").replace(']', ''))

here is some improvement:

favourite_places = {
    "Jozefína": ["Amsterdam", "Liverpool", "London"],
    "Marek": ["Košice"],
    "Jozef": ["Lisabon", "Vancouver"]
}


for name, place in favourite_places.items():
    line = ', '.join(place)
    print(f'{name} likes to go to here: {line}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM