我有以下列表和字符串:
befcodes = ["A1","A2","A3","A4","A5","A6","A7","A8","A9","10","11","12","13","14","15","16","17","18","19","20"]
telegram = "$00;02;A1;00000000*49"
现在,我的代码将字符串中的A1
更改为20次,如下所示:allbefcodes = []
for i in befcodes:
dif_tele = telegram.replace("A1", i)
allbefcodes.append(dif_tele)
print (allbefcodes)
输出以下列表:['$00;02;A1;00000000*49', '$00;02;A2;00000000*49', '$00;02;A3;00000000*49', '$00;02;A4;00000000*49', '$00;02;A5;00000000*49', '$00;02;A6;00000000*49', '$00;02;A7;00000000*49', '$00;02;A8;00000000*49', '$00;02;A9;00000000*49', '$00;02;10;00000000*49', '$00;02;11;00000000*49', '$00;02;12;00000000*49', '$00;02;13;00000000*49', '$00;02;14;00000000*49', '$00;02;15;00000000*49', '$00;02;16;00000000*49', '$00;02;17;00000000*49', '$00;02;18;00000000*49', '$00;02;19;00000000*49', '$00;02;20;00000000*49']
现在,我想使用XOR运算符来获取每个电报的二进制校验和(= allbefcodes
的每个字符),我这样做是这样的:result = functools.reduce(operator.xor,(ord(n) for n in (allbefcodes[0])[1:18]))
print (f'{result:08b}')
这对于allbefcodes[0]
确实可以正常工作,我得到了输出01001001
。但是我现在想通过循环对allbefcodes
的所有字符执行此操作,在此我会遇到不同的错误.. 这是到目前为止我尝试过的操作:for x in allbefcodes:
result = functools.reduce(operator.xor,(ord(n) for n in (allbefcodes[x])[1:18]))
print (f'{result:08b}')
错误TypeError: list indices must be integers or slices, not str
发生。我试图这样解决:for x in allbefcodes:
allbefcodes = (int(a) for a in allbefcodes)
result = functools.reduce(operator.xor,(ord(n) for n in (allbefcodes[x])[1:18])) # "
print (f'{result:08b}')
但是这里会出现错误TypeError: 'generator' object is not subscriptable
。所以我接下来尝试了这个:allbefcodes = []
for i in befcodes:
dif_tele = telegram.replace("A1", i)
allbefcodes.append(dif_tele)
allbefcodes = (int(a) for a in allbefcodes) #Tried to solve it with this line
print (allbefcodes)
for x in allbefcodes:
result = functools.reduce(operator.xor,(ord(n) for n in (allbefcodes[x])[1:18])) # "(allbefcodes[0])" statt telegram
print (f'{result:08b}')
但是现在出现了ValueError: invalid literal for int() with base 10: '$00;02;A1;00000000*49'
错误。进行(float(int(a)) for a in allbefcodes)
不会改变这一点。我的最后一次尝试是将
(allbefcodes[x])
更改为(allbefcodes[0:])
并保留allbefcodes = (int(a) for a in allbefcodes)
,如下所示:allbefcodes = []
for i in befcodes:
dif_tele = telegram.replace("A1", i)
allbefcodes.append(dif_tele)
print (allbefcodes)
for x in allbefcodes:
result = functools.reduce(operator.xor,(ord(n) for n in (allbefcodes[0:])[1:18])) # "(allbefcodes[0])" statt telegram
print (f'{result:08b}')
但是现在我得到了TypeError: ord() expected a character, but string of length 21 found
,这使我又回到了整数而不是字符串的问题,我已经尝试解决了……我真的不知道该怎么办了,非常感谢您的帮助! 最佳答案
我想到了!
我只需要像这样用(allbefcodes[0:])
替换x
:
allbefcodes = []
for i in befehlscodes:
dif_tele = telegram.replace("A1", i)
allbefcodes.append(dif_tele)
print (allbefcodes)
for x in allbefcodes:
result = functools.reduce(operator.xor,(ord(n) for n in x[1:18]))