如何用Python将文件中数字转为整数并拆分多位数为单个元素?
Got it, let's tackle this problem step by step. Here's how you can read your text file, process each line to split multi-digit numbers into individual digits, and convert everything to integers:
Solution Code
# Replace 'your_file.txt' with the actual path to your text file with open('your_file.txt', 'r') as file: processed_lines = [] for line in file: # Clean the line and split into separate number strings num_strings = line.strip().split() # Split each number into individual digits and convert to integers digit_list = [int(char) for num in num_strings for char in num] processed_lines.append(digit_list) # Example: Print the processed results for idx, line in enumerate(processed_lines, 1): print(f"Processed line {idx}: {line}")
How This Works
Let’s break down the key parts so you understand what’s happening:
- File Handling: Using
with open(...)is Python’s recommended way to work with files—it takes care of closing the file automatically, so you don’t have to worry about resource leaks. - Line Cleaning & Splitting:
line.strip()removes extra whitespace (like newlines at the end of the line), then.split()breaks the line into a list of number strings. For your example input"3 4 1 8 7 6 41", this gives us["3", "4", "1", "8", "7", "6", "41"]. - Splitting Multi-Digit Numbers: The nested list comprehension
[int(char) for num in num_strings for char in num]loops through each number string first, then loops through each character in that string. It converts each character to an integer, so"41"becomes4and1as separate integer elements. - Storing Results: We collect each processed line’s digit list into
processed_lines, which you can use for further calculations or output.
Example Output
If your text file has one line with "3 4 1 8 7 6 41", the code will output:
Processed line 1: [3, 4, 1, 8, 7, 6, 4, 1]
内容的提问来源于stack exchange,提问作者ProgFacts
相关产品推荐
相关产品推荐

