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

如何将文件每行前两个值作为键、后两个作为值生成字典

Got it, let's work through this to get your target dictionary sorted! You've got two variations of your input list, so I'll break down how to handle each one step by step.

1. 处理每行作为单个元素的 v_list

Your first list looks like this:

v_list = ['a b 1 2','d e 2 3','a c 4 6']

Here's how to turn this into your desired dictionary:

  • Loop through each string in the list
  • Split each string into its individual components (using split(), which handles spaces automatically)
  • Take the first two components, join them with a - to make your key
  • Take the last two components, convert them to integers, and pack them into a tuple for the value
  • Add each key-value pair to your dictionary

Code example:

d = {}
for item in v_list:
    parts = item.split()
    # 前两个元素拼接成键
    key = f"{parts[0]}-{parts[1]}"
    # 后两个元素转整数组成元组
    value = (int(parts[2]), int(parts[3]))
    d[key] = value

print(d)
# Output: {'a-b': (1, 2), 'd-e': (2, 3), 'a-c': (4, 6)}

2. 处理每个值作为独立元素的 v_list

Your second list is flattened, like this:

v_list = ['a','b','1','2','d','e','2','3','a','c','4','6']

Since each "row" of data takes up 4 consecutive elements, we can loop through the list in steps of 4:

  • Use range(0, len(v_list), 4) to get starting indices for each group of 4 elements
  • For each starting index, slice the list to get the 4 elements for that row
  • Repeat the same key/value logic as above

Code example:

d = {}
# 每4个元素为一组处理
for i in range(0, len(v_list), 4):
    # 取出当前组的4个元素
    group = v_list[i:i+4]
    key = f"{group[0]}-{group[1]}"
    value = (int(group[2]), int(group[3]))
    d[key] = value

print(d)
# Output: {'a-b': (1, 2), 'd-e': (2, 3), 'a-c': (4, 6)}

Quick Bonus Tip

If you're reading directly from file_name.txt, you can skip creating those intermediate lists entirely and build the dictionary on the fly:

d = {}
with open('file_name.txt', 'r') as f:
    for line in f:
        parts = line.strip().split()
        if len(parts) == 4:  # 确保每行格式正确,避免报错
            key = f"{parts[0]}-{parts[1]}"
            value = (int(parts[2]), int(parts[3]))
            d[key] = value

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:56:55