如何将Python中三行split代码合并为一行?
Streamline Mouse Coordinate Extraction into One Line
Got it, let's turn those three split lines into a single concise line of code. Here are two clean approaches you can use:
Approach 1: List Comprehension (No Extra Dependencies)
This method builds on your original split logic but condenses it into one line:
x_ret, y_ret = [coord.split(':')[1] for coord in text.split(' ', 2)[:2]]
How it works:
text.split(' ', 2)splits your input string into 3 parts:['x:3400', 'y:558', 'screen:0 window:23073340'][:2]grabs just the first two elements (x:...andy:...)- The list comprehension runs
split(':')[1]on each of those two elements to extract the numeric value after the colon - Finally, we unpack the resulting list directly into
x_retandy_ret
Approach 2: Regular Expressions (Even Cleaner)
If you're okay using Python's built-in re module, this method cuts straight to the chase by matching the numeric values directly:
import re x_ret, y_ret = re.findall(r'[xy]:(\d+)', text)
How it works:
- The regex pattern
[xy]:(\d+)matches eitherx:ory:followed by one or more digits re.findall()returns a list of the captured numeric values, which we unpack intox_retandy_ret
Full Example with subprocess
Here's how this fits into your full workflow using xdotool:
import subprocess # Optional: import re for the regex approach result = subprocess.run(['xdotool', 'getmouselocation'], capture_output=True, text=True) text = result.stdout.strip() # Use either approach here: x_ret, y_ret = [coord.split(':')[1] for coord in text.split(' ', 2)[:2]] # OR # x_ret, y_ret = re.findall(r'[xy]:(\d+)', text) print(f"x-offset: {x_ret} y-offset: {y_ret}")
Both methods will give you the same output as your original three lines, just in a more compact form.
内容的提问来源于stack exchange,提问作者WinEunuuchs2Unix
相关产品推荐
相关产品推荐

