[Tutor] Is there a better way to write my code?
Mark Lawrence
breamoreboy at gmail.com
Mon Aug 13 16:21:22 EDT 2018
On 13/08/18 16:53, Rafael Knuth wrote:
> I wrote this code below which aims to concatenate strings with their
> respective string length.
> I was wondering if there is a shorter, more elegant way to accomplish this task.
> 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]]
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
For a definition of better:-
animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
animals_lol = []
for animal in animals:
animals_lol.append((animal, len(animal)))
print(animals_lol)
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list