You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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:

  1. text.split(' ', 2) splits your input string into 3 parts: ['x:3400', 'y:558', 'screen:0 window:23073340']
  2. [:2] grabs just the first two elements (x:... and y:...)
  3. The list comprehension runs split(':')[1] on each of those two elements to extract the numeric value after the colon
  4. Finally, we unpack the resulting list directly into x_ret and y_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 either x: or y: followed by one or more digits
  • re.findall() returns a list of the captured numeric values, which we unpack into x_ret and y_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:47:54