如何将指定文本文件转换为{键: [数值列表]}格式的dictionary变量?
Convert Text File to Min-Cut Dictionary
Got it! Let's turn your text file into the dictionary format you need. Here's a simple Python solution that does exactly what you're asking for:
def create_mincut_dict(file_path): mincut_dict = {} with open(file_path, 'r') as f: for line in f: # Clean up the line and convert all values to integers nodes = list(map(int, line.strip().split())) if nodes: # Skip any empty lines in the file key_node = nodes[0] adjacent_nodes = nodes[1:] mincut_dict[key_node] = adjacent_nodes return mincut_dict # Example usage: # Replace 'kargerMinCut.txt' with the actual path to your file final_dict = create_mincut_dict('kargerMinCut.txt') # Print a sample to verify the format print(f"Sample entry: 1 -> {final_dict[1]}")
How this works:
- File Handling: We use a
withstatement to open the file safely—this ensures the file is automatically closed after processing, even if an error occurs. - Line Processing: Each line is stripped of extra whitespace and split into individual elements, which we convert to integers (since your nodes are numeric).
- Dictionary Construction: The first number in each line becomes the dictionary key, and all subsequent numbers form the list of adjacent nodes for that key.
- Edge Case Handling: We skip empty lines to avoid errors, though your input file likely doesn't have any.
This will output a dictionary exactly in the format you specified: {1: [37, 79, ..., 196], ..., 200: [149,...,35]}.
内容的提问来源于stack exchange,提问作者user5335342
相关产品推荐
相关产品推荐

