Python 3.8中如何从galois库的GF对象结果中提取列表?
问题
在Python 3.8中执行以下代码:
import galois GF = galois.GF(2) f = galois.Poly([1,0,0,1], field=GF) g = galois.Poly([1,1,0], field=GF) c=f * g d=c.coeffs
得到输出:
d=GF([1, 1, 0, 1, 1, 0], order=2)
需要将d转换为纯列表形式:[1,1,0,1,1,0]。尝试以下代码提取时出现错误:
v=list(str(d)) u=[ int(x) for s in v for x in s.split(',')]
错误信息:
invalid literal for int() with base 10: '['
解决方法
推荐方法:直接转换为普通列表
d是galois.GF类型的数组,无需通过字符串处理,直接用内置方法即可转换为纯整数列表:
# 方式1:使用list()函数 result = list(d) print(result) # 输出: [1, 1, 0, 1, 1, 0] # 方式2:调用tolist()方法 result = d.tolist() print(result) # 输出: [1, 1, 0, 1, 1, 0]
备选方法:修复字符串处理逻辑(不推荐)
如果一定要通过字符串提取,需先过滤无效字符再拆分转换:
# 提取括号内的内容并处理 content = str(d).split('[')[1].split(']')[0] result = [int(item.strip()) for item in content.split(',')] print(result) # 输出: [1, 1, 0, 1, 1, 0]
此方法依赖库的输出格式,若后续版本格式变化会失效,优先使用推荐方法。
内容的提问来源于stack exchange,提问作者SHASHANK RANJAN
相关产品推荐
相关产品推荐

