如何将列表元素转为int并与数字比较?txt文件数值比对报错求助
Hey there! Let’s break down why your number comparison is failing and fix it up—this is super common when working with text files, so you’re not alone here.
The Most Likely Culprit: String vs. Numeric Types
When you read data from a text file, everything comes in as strings by default. If you stored those strings directly in your dictionary, comparing them to the number 70 won’t work the way you expect. For example, Python will treat "100" < "70" as True because it compares character ASCII values, not actual numeric values.
Fix Step 1: Convert Values to Numbers When Building the Dictionary
Let’s assume your text file has lines formatted like key 65 (space-separated key and value). Here’s how to properly read and convert the values:
my_dict = {} with open('your_file.txt', 'r') as file: for line in file: # Split line into parts, handling extra spaces line_parts = line.strip().split() if len(line_parts) >= 2: key = line_parts[0] # Try converting to float (works for integers and decimals) try: numeric_value = float(line_parts[1]) my_dict[key] = numeric_value except ValueError: # Catch cases where the value isn't a valid number print(f"Warning: Couldn't convert '{line_parts[1]}' to a number for key '{key}'")
Fix Step 2: Perform the Comparison Correctly
Now that your dictionary holds actual numbers, the comparison will work as intended:
# Check each value in the dictionary for key, value in my_dict.items(): if value < 70: print(f"Key '{key}' has a value ({value}) that's less than 70") else: print(f"Key '{key}' has a value ({value}) that's 70 or higher")
If Your File Has Multiple Values Per Key
If each line has a key followed by multiple space-separated numbers (like key 50 75 62), adjust the code to handle lists of numbers:
my_dict = {} with open('your_file.txt', 'r') as file: for line in file: line_parts = line.strip().split() if line_parts: key = line_parts[0] numeric_values = [] for val_str in line_parts[1:]: try: numeric_values.append(float(val_str)) except ValueError: print(f"Skipping invalid value '{val_str}' for key '{key}'") my_dict[key] = numeric_values # Check each value in the lists for key, values in my_dict.items(): print(f"\nChecking values for key '{key}':") for val in values: status = "is less than 70" if val < 70 else "is 70 or higher" print(f"- {val} {status}")
Quick Debug Tip
If you’re still unsure, print the type of a value in your dictionary to confirm:
print(type(my_dict['some_key'])) # Should output <class 'float'> or <class 'int'>, not <class 'str'>
内容的提问来源于stack exchange,提问作者Pankaj_Dwivedi

