Python中使用enumerate存值入列表及获取对象长度等问题咨询
Hey there! Let's break down your questions one by one, with practical examples tailored to your code:
enumerate to store values in a list enumerate() is super handy when you need both the index and the value while iterating. Here are common ways to use it to populate a list:
Scenario 1: Store values with conditional checks
If you only want to keep certain values based on their index,enumeratelets you do that easily:fruits = ["apple", "banana", "cherry", "date"] filtered_fruits = [] for idx, fruit in enumerate(fruits): # Keep fruits at odd indices if idx % 2 == 1: filtered_fruits.append(fruit) print(filtered_fruits) # Output: ['banana', 'date']Scenario 2: Store index-value pairs
You can directly convert theenumerateresult to a list of tuples:fruits = ["apple", "banana", "cherry"] indexed_fruits = list(enumerate(fruits)) print(indexed_fruits) # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
First, let's refactor your list comprehension into a reusable variable (since you don't want to just print it):
# Store the result instead of printing it immediately detection_results = [category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > 0.5]
1. How to get the length of this object?
Use Python's built-in len() function—it works for all iterable objects with a defined length (like lists, tuples, dictionaries):
result_length = len(detection_results) print(result_length) # Prints the number of items in the list
2. How to store only the item names in a new list?
Assuming category_index.get(value) returns a dictionary (e.g., {"name": "cat", "id": 1}) or an object with a name attribute, you just need to extract that field in your list comprehension:
If it's a dictionary:
item_names = [result["name"] for result in detection_results if result is not None] # The "if result is not None" avoids errors if category_index.get(value) returns None
If it's a custom object with a name attribute:
item_names = [result.name for result in detection_results if result is not None]
Alternatively, you can do it directly in one line (without the intermediate detection_results variable):
item_names = [ category_index.get(value)["name"] for index, value in enumerate(classes[0]) if scores[0, index] > 0.5 and category_index.get(value) is not None ]
内容的提问来源于stack exchange,提问作者basviccc

