Reputation: 11
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]
Upvotes: 0
Views: 49
Reputation: 46
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]}
Upvotes: 0
Reputation: 24289
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]
Upvotes: 2