You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python复杂字典转列表求助:路径动作值计算问题

解决字典列表中动作路径的分值计算问题

Hey there! No worries at all—let's break this down step by step since you're new to Python and working with dictionaries/lists here. 😊

From what you shared, it looks like you need to calculate the total score for each path in your frontier list using the predefined action values. Here's a straightforward, easy-to-follow way to do this:

Step 1: Define the action-to-score mapping

First, we'll create a dictionary to map each action to its corresponding score—this makes looking up values quick, clean, and easy to modify later if needed:

action_scores = {'PUSH': 5, 'PULL': 6, 'SWAP': 8, 'FLIP': 2}

Step 2: Calculate scores for each entry

Next, we'll loop through each dictionary in your frontier list, compute the total score for its path, and either print the result or add it directly to the dictionary (whichever fits your needs):

Option 1: Print results without modifying the original data

This is great if you just want to view the scores right away:

frontier = [
    { 'state': (2, 5, 4, 3, 0, 1), 'path': [ 'PULL' ] },
    { 'state': (2, 4, 5, 0, 3, 1), 'path': [ 'SWAP','PULL' ] },
    { 'state': (2, 5, 4, 0, 1, 3), 'path': [ 'SWAP' ] },
    { 'state': (2, 0, 5, 4, 3, 1), 'path': [ 'PUSH', 'PUSH' ] },
]

for entry in frontier:
    state = entry['state']
    path = entry['path']
    # Use sum() with a generator to quickly add up action scores
    total_score = sum(action_scores[action] for action in path)
    print(f"State: {state} | Path: {path} | Total Score: {total_score}")

Running this will output:

State: (2, 5, 4, 3, 0, 1) | Path: ['PULL'] | Total Score: 6
State: (2, 4, 5, 0, 3, 1) | Path: ['SWAP', 'PULL'] | Total Score: 14
State: (2, 5, 4, 0, 1, 3) | Path: ['SWAP'] | Total Score: 8
State: (2, 0, 5, 4, 3, 1) | Path: ['PUSH', 'PUSH'] | Total Score: 10

Option 2: Add the total score to the original dictionaries

If you want to keep the score attached to each entry for later processing, you can update the dictionaries directly:

for entry in frontier:
    entry['total_score'] = sum(action_scores[action] for action in entry['path'])

# View the updated frontier list
print(frontier)

This will modify each dictionary in frontier to include a new total_score key with the calculated value.


内容的提问来源于stack exchange,提问作者Alex Ham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:18:20