从.txt文件读取值后出现KeyError,求原因及解决方法
Let's break down the problem first—your error comes from a mismatch in the data structure you're reading vs. what your code expects.
Looking at your program output:
[(1, 2, 3, 4, 5)]
[(1, 2), (1, 3), (2, 3), (3, 5), (5, 4)]
The first line shows that A (your vertex list) is a list containing a single tuple, not the flat list of integers [1,2,3,4,5] you had in your commented-out code.
Here's why that causes the KeyError:
- When you initialize
indegreeandoutdegree, you loop through elements inA. Right now,Aonly has one element: the tuple(1,2,3,4,5). So your dictionaries end up with one key: that entire tuple, not the individual integers 1,2,3,4,5. - Later, when you iterate over edges in
B(like(1,2)), you try to incrementoutdegree[1]—but 1 isn't a key inoutdegree(only the tuple is), hence the KeyError.
Two Easy Fixes:
1. Modify your v.txt file (cleanest solution)
Change the content of v.txt to be a flat list of integers instead of a list with a tuple:
[1,2,3,4,5]
This way, ast.literal_eval will read it directly into the same structure as your original commented-out V variable, and your code will work without changes.
2. Adjust the code to handle the existing file structure
If you can't edit the text file, add a line to unpack the tuple from the list:
import ast with open('v.txt') as V: A = ast.literal_eval(V.read()) # Unpack the tuple inside the list into a flat integer list A = list(A[0]) # Add this line with open('e.txt') as E: B = ast.literal_eval(E.read()) print(A) print(B) indegree = {} outdegree = {} for x in A: indegree[x] = 0 outdegree[x] = 0 for x,y in B: outdegree[x] += 1 indegree[y] += 1 for x in A: print("Outdegree for vertex", x,"=", outdegree[x]) print("Indegree for vertex", x,"=", indegree[x])
After either fix, A will be the flat integer list your code expects, and the KeyError will disappear.
内容的提问来源于stack exchange,提问作者teddy

