我有两个列表,如下例所示:
result_primary = ['00000000', '01010101', '10101010', '11111111']
result_compressed = ['01100110', '10011001']
我正在计算第二个列表中的每个元素与第一个列表中的每个元素之间的汉明距离,为此我编写了以下代码:
def hamming2(s1, s2):
assert len(s1) == len(s2)
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
for i in result_primary:
for j in result_compressed:
primary_att_vs_compr_hamming = np.array([i, j, hamming2(i, j)] )
print(primary_att_vs_compr_hamming)
这将在控制台上显示所需的结果:
['00000000' '01100110' '4']
['00000000' '10011001' '4']
['01010101' '01100110' '4']
['01010101' '10011001' '4']
['10101010' '01100110' '4']
['10101010' '10011001' '4']
['11111111' '01100110' '4']
['11111111' '10011001' '4']
但实际上,我并没有将所有数据都记录在数组中,而是在每次迭代中覆盖变量,最后我只将最后一行写入数组:
def hamming2(s1, s2):
assert len(s1) == len(s2)
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
for i in result_primary:
for j in result_compressed:
primary_att_vs_compr_hamming = np.array([i, j, hamming2(i, j)] )
print(primary_att_vs_compr_hamming)
输出:
['11111111' '10011001' '4']
我怎样才能把所有的东西都写进数组中(因为我愿意把它用于进一步的操作)?还有,我怎样才能把列的标题放进数组中(不管怎么说,它是字符串数组)?
1条答案
按热度按时间m528fe3b1#
使用外部列表存储结果:
输出: