为何Python针对同一数据集会产生不同结果?附代码及控制台输出
Let's break down what's happening here — the "different results" you're seeing are actually just display and output formatting differences, not Python processing the dataset differently. Here's the breakdown:
1. Console output truncation is a display limitation
When you print a long dictionary (like your neighbor.attrib) directly to the console, Python automatically truncates the string with ... to prevent flooding the terminal with too much text. This is purely a UI optimization — the actual data stored in the dictionary is still complete.
To verify this, try printing the specific value you care about instead of the whole dictionary:
print(neighbor.attrib['refId'])
This will show you the full, untruncated string of the refId attribute. For nicer formatted full output of dictionaries, use the pprint module:
from pprint import pprint pprint(neighbor.attrib)
pprint will format the dictionary neatly and avoid unnecessary truncation.
2. File output has a different behavior (and might not be what you expect)
Your code uses csv.writer.writerow(neighbor.attrib) — but when you pass a dictionary to writerow(), it writes the keys of the dictionary as a row, not the key-value pairs. That's a common gotcha!
If you want to write the actual attribute values (like the full refId string) to your file, you should explicitly access the value:
writer.writerow([neighbor.attrib['refId']])
Or if you want all key-value pairs, you can write them as separate columns:
writer.writerow(neighbor.attrib.items())
Unlike the console, the file output doesn't truncate data — it writes the complete raw values, so your data.txt should have the full attribute strings even if the console print looks truncated.
So to sum up: Python isn't producing different results for the same dataset — it's just displaying/writing the data in different ways depending on the output target.
内容的提问来源于stack exchange,提问作者ASH

