简体   繁体   中英

Comparing List / CSV File Python

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]

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]

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]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM