检索存储为列表中字符串的复数的实部和虚部
Retrieving real and imaginary part of complex numbers stored as strings in a list
我这样做是为了恢复字符串的第一部分,例如:“13+i”的“13”:
l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l2 = [i.split('+')[0] for i in l1]
l2 = list(map(int, l2))
它运行良好,然后我想要“13+i”中的“1”,但自从字符串中的 "i" 没有“1”因子以来,它变得更加复杂。
我应该得到:
[1, 4, 2, 4, 1, 2, 4]
即数组中只有复数的虚部。
有什么办法可以帮助我解决这个问题吗?
Python 有处理复数的方法;它实际上有一个类型(<class 'complex'>
)。因此,为了避免重新发明轮子,我强烈建议使用它。
为此,我们必须首先 清理 我们的输入(将值从 strings
转换为 complex
)。为此,我们必须首先遵守 Python 对 虚数单位 的约定,其中使用 'j'
而不是 'i'
.
l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l1 = [complex(x.replace('i', 'j')) for x in l1]
# if you are curious how they look like
print(l1)
# -> [(13+1j), (1+4j), ...]
有了正确格式的值,我们可以利用 complex
类型变量的 .real
and .imag
attributes 并使用列表比较构建我们的结果列表。
real_parts = [value.real for value in l1]
print(real_parts)
# -> [13.0, 1.0, 3.0, 11.0, 5.0, 10.0, 5.0]
imaginary_parts = [value.imag for value in l1]
print(imaginary_parts)
# -> [1.0, 4.0, 2.0, 4.0, 1.0, 2.0, 4.0]
请注意,默认情况下,它们都是实数(非整数时为实数)。使用 [int(value.real) for value in l1]
.
可以轻松实现将它们转换为 int
可能关于使用现有功能的最好的事情是您不必担心您可能没有的边缘情况,但可能会导致您的代码打破。例如 4j
(无实部)或 1-j
(负虚部,因此 .split('+')[0]
无效)等等。
python 复数类型使用 j 而不是 i 来表示复数。
因此,
i=['13+i','1+4i','3+2i','11+4i','5+i','10+2i','5+4i']
real_parts=[ complex(x.replace("i", "j")).real for x in i]
imaginary_parts=[ complex(x.replace("i", "j")).imag for x in i ]
正是您要找的。
我这样做是为了恢复字符串的第一部分,例如:“13+i”的“13”:
l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l2 = [i.split('+')[0] for i in l1]
l2 = list(map(int, l2))
它运行良好,然后我想要“13+i”中的“1”,但自从字符串中的 "i" 没有“1”因子以来,它变得更加复杂。
我应该得到:
[1, 4, 2, 4, 1, 2, 4]
即数组中只有复数的虚部。
有什么办法可以帮助我解决这个问题吗?
Python 有处理复数的方法;它实际上有一个类型(<class 'complex'>
)。因此,为了避免重新发明轮子,我强烈建议使用它。
为此,我们必须首先 清理 我们的输入(将值从 strings
转换为 complex
)。为此,我们必须首先遵守 Python 对 虚数单位 的约定,其中使用 'j'
而不是 'i'
.
l1 = ['13+i', '1+4i', '3+2i', '11+4i', '5+i', '10+2i', '5+4i']
l1 = [complex(x.replace('i', 'j')) for x in l1]
# if you are curious how they look like
print(l1)
# -> [(13+1j), (1+4j), ...]
有了正确格式的值,我们可以利用 complex
类型变量的 .real
and .imag
attributes 并使用列表比较构建我们的结果列表。
real_parts = [value.real for value in l1]
print(real_parts)
# -> [13.0, 1.0, 3.0, 11.0, 5.0, 10.0, 5.0]
imaginary_parts = [value.imag for value in l1]
print(imaginary_parts)
# -> [1.0, 4.0, 2.0, 4.0, 1.0, 2.0, 4.0]
请注意,默认情况下,它们都是实数(非整数时为实数)。使用 [int(value.real) for value in l1]
.
int
可能关于使用现有功能的最好的事情是您不必担心您可能没有的边缘情况,但可能会导致您的代码打破。例如 4j
(无实部)或 1-j
(负虚部,因此 .split('+')[0]
无效)等等。
python 复数类型使用 j 而不是 i 来表示复数。
因此,
i=['13+i','1+4i','3+2i','11+4i','5+i','10+2i','5+4i']
real_parts=[ complex(x.replace("i", "j")).real for x in i]
imaginary_parts=[ complex(x.replace("i", "j")).imag for x in i ]
正是您要找的。