0

I have two lists:

description_list = [Cat, Cat, Bat, Horse, Bat, Cow, Pig, Pig]
time_list = [6, 8, 10, 8, 7, 1, 0, 0]

These lists were created from a CSV file. For example: Cat matches with the number 6 and 8, Bat matches with 10 and 7, and so on.

How do I create a new list called cat_time where I have a list of all of the Cat time values. For example:

cat_time = [6, 8]
1
  • 2
    [t for d, t in zip(descriptions, times) if d == "Cat"] Commented Dec 9, 2019 at 17:50

2 Answers 2

2

You should use a dict rather than try to create separate variables:

from collections import defaultdict

description_list = ['Cat', 'Cat', 'Bat', 'Horse', 'Bat', 'Cow', 'Pig', 'Pig']
time_list = [6, 8, 10, 8, 7, 1, 0, 0]

times = defaultdict(list)
for time, desc in zip(time_list, description_list):
    times[desc].append(time)

print(times)
# defaultdict(<class 'list'>, {'Cat': [6, 8], 'Bat': [10, 7], 'Horse': [8], 'Cow': [1], 'Pig': [0, 0]})

print(times['Cat'])
# [6, 8]
Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend using list comprehension. For example, to find cat_time:

cat_list = [time_list[i] for i in range(len(description_list)) if description_list[i] == 'Cat']

If you want all the lists in a dictionary, could also do:

animals_lists = {}
for animal in set(description_list):
    animals_lists[animal] = [time_list[i] for i in range(len(description_list)) if description_list[i] == animal]

Which will return:

animals_lists = {'Cat': [6, 8], 'Pig': [0, 0], 'Bat': [10, 7], 'Horse': [8], 'Cow': [1]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.