[Tutor] Is there a better way to write my code?
Nitin Madhok
nmadhok at g.clemson.edu
Mon Aug 13 20:54:18 EDT 2018
Use List comprehension:
animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]
animals_lol = [[animal, len(animal)] for animal in animals]
print(animals_lol)
[['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]
If you want to read more about list comprehension, https://www.pythonforbeginners.com/lists/list-comprehensions-in-python/ <https://www.pythonforbeginners.com/lists/list-comprehensions-in-python/> is a good resource!
--
Thanks,
Nitin Madhok
Clemson University
CONFIDENTIALITY NOTICE
This e-mail, and any attachments thereto, is intended only for use by the addressee(s) named herein and may contain privileged and/or confidential information. If you are not the intended recipient of this e-mail, any dissemination, distribution or copying of this e-mail, and any attachments thereto, is strictly prohibited. If you have received this e-mail in error, please immediately notify the sender by e-mail or telephone and permanently delete all copies of this e-mail and any attachments.
> On Aug 13, 2018, at 11:53 AM, Rafael Knuth <rafael.knuth at gmail.com> 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
More information about the Tutor
mailing list