一、字典是由键值对(key-value)组成的
因为 results[num] = {...}
这种写法是通过键(这里是 num
)为 results
赋值,results
就是一个字典(dict)。
在 Python 里,字典是由键值对(key-value)组成的,像这样:
results = {}
results[1] = {"action_name": "xxx"}
这样 results
就是 {1: {"action_name": "xxx"}}
,每个 num
都对应一个字典。
而不是像列表那样用下标存放元素。
排序
# Sort by the extracted number
results.sort()
二、数组的数组
## 容易变为数组的数组
#results = []
##这是“数组的数组”(更准确地说,是 Python 的列表的列表),不是字典。
#每个内部列表包含多个元素(数字、字符串等),而不是键值对结构。
results.append((num, action_name, duration, resource_id,action_vector_first))
排序
#results = dict(sorted(results.items()))
使用
You can use this list of lists (array of arrays) by accessing elements with indexes. For example, to get the action name of the first item:
# results is your list of lists
action_name = results[0][1] # "_片段010"
duration = results[0][2] # "1.93s"
resource_id = results[0][3] # "5984-3ac3a7ba2ef3"
vector = results[0][4] # "10111111"
To loop through all items and print each action name:
for item in results:
print(item[1]) # Prints the action_name
To find an item by number:
num_to_find = 11
for item in results:
if item[0] == num_to_find:
print(item) # Prints the whole sublist for num 11
This structure is suitable for ordered data and easy iteration.
三、 二者对比
You are comparing two data structures for storing action information: a dictionary (dict
) and a list of lists/tuples (an “array of arrays” or “list of lists/tuples” in Python).
1. Dictionary (dict
)
- Usage:
results = {} results[num] = { "action_name": action_name, "duration": duration, "resource_id": resource_id, "action_vector_first": action_vector_first }
- Features:
- Fast lookup by
num
(the key). - Each entry is a dictionary, so you can access fields by name (e.g.,
results[23]["action_name"]
). - Good for when you need to access items by a unique identifier or want to avoid duplicates.
- Fast lookup by
2. List of Tuples (Array of Arrays)
- Usage:
results = [] results.append((num, action_name, duration, resource_id, action_vector_first))
- Features:
- Ordered collection; you can sort or iterate in order.
- Each entry is a tuple/list, so you access fields by index (e.g.,
results[0][1]
foraction_name
). - Good for when order matters or you want to allow duplicates.
How to Choose
- Use a dict if you want to look up actions by
num
quickly, or ifnum
is unique. - Use a list of tuples if you care about order, want to allow duplicate
num
, or need to sort by different fields.
Example: Accessing Data
- Dict:
# Get action_name for num=23 action_name = results[23]["action_name"]
- List of Tuples:
# Get action_name for the first item action_name = results[0][1]
Summary:
- Use a dict for fast, key-based access and unique keys.
- Use a list of tuples for ordered, index-based access and possible duplicates.