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

如何从字符串形式的复数列表中提取虚部系数(含隐式1)

提取复数虚部系数的解决方法

嘿,这个问题我之前处理复数字符串的时候也遇到过,确实因为那个省略的1有点棘手,不过有两种实用的方法可以搞定,我给你详细说说:

方法一:直观的字符串分割与判断

这种方法适合你当前的输入格式(都是a+bi或a+i的正系数形式),思路很直接:

  1. 把每个复数字符串按+分割,取出后面的虚部片段
  2. 如果虚部是纯i,说明系数是1;否则去掉末尾的i,转成整数

代码实现(循环版,易读)

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
imag_coeffs = []
for complex_str in l1:
    imag_part = complex_str.split('+')[1]
    if imag_part == 'i':
        imag_coeffs.append(1)
    else:
        imag_coeffs.append(int(imag_part[:-1]))

print(imag_coeffs)  # 输出: [1, 4, 2, 4, 1, 2, 4]

代码实现(列表推导式,简洁)

如果喜欢更紧凑的写法,用列表推导式一行搞定:

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
imag_coeffs = [1 if part == 'i' else int(part[:-1]) for part in (s.split('+')[1] for s in l1)]

方法二:正则表达式(适配更复杂场景)

如果以后你的复数格式可能变化(比如出现负虚部'13-i'、虚部在前'i+13'等),正则表达式会更通用。我们可以用正则精准匹配虚部的系数:

正则r'\+(\d*)i'会匹配+后面的0个或多个数字(对应系数),再跟着i。如果是+i的情况,匹配到的系数是空字符串,我们只需要把空值替换成1即可。

代码实现

import re

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
pattern = re.compile(r'\+(\d*)i')
imag_coeffs = []
for complex_str in l1:
    match_result = pattern.search(complex_str)
    coeff_str = match_result.group(1)
    imag_coeffs.append(1 if coeff_str == '' else int(coeff_str))

print(imag_coeffs)  # 输出: [1, 4, 2, 4, 1, 2, 4]

代码实现(列表推导式版)

同样可以写成简洁的列表推导式:

import re

l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
pattern = re.compile(r'\+(\d*)i')
imag_coeffs = [1 if g == '' else int(g) for g in (pattern.search(s).group(1) for s in l1)]

内容的提问来源于stack exchange,提问作者GabrielT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:01:33