[Tutor] Is there a better way to write my code?
Rafael Knuth
rafael.knuth at gmail.com
Tue Aug 14 02:56:29 EDT 2018
> I wrote this code below
> I was wondering if there is a shorter, more elegant way to accomplish this task.
> Thanks!
thank you so much everyone!
List comprehension is really cool. One thing I like about list
comprehension is that you can get a dictionary, tuples or lists as a
result by just changing the type of braces.
# dictionary
colors = ["red", "blue", "white", "yellow"]
colors_len = [{color, len(color)} for color in colors]
print(colors_len)
# tuples
colors = ["red", "blue", "white", "yellow"]
colors_len = [(color, len(color)) for color in colors]
print(colors_len)
# lists
colors = ["red", "blue", "white", "yellow"]
colors_len = [[color, len(color)] for color in colors]
print(colors_len)
Can you shed some light on when to use which of the above data structures?
I assume there is no simple answer to that question, I am still trying
to understand the fundamentals of Python (which happens to be my first
programming language). Thanks!
> animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
>
> # step one: convert the animal list into a list of lists
>
> animals_lol = []
>
> for animal in animals:
> animal_split = animal.split(",")
> animals_lol.append(animal_split)
>
> # step two: collect the length of each string in a separate list
>
> animals_len = []
>
> for animal in animals:
> animals_len.append(len(animal))
>
> # step three: append the length of each string to the list of lists
>
> for a, b in enumerate(animals_lol):
> b.append(animals_len[a])
>
> print(animals_lol)
>
> [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
More information about the Tutor
mailing list