python中的for循环和in运算符

简历

我试图理解用 python 编写的现有代码。我目前正在学习python。有人可以帮我理解这段代码吗?

bits_list = split_string_into_chunks(coding, n)
# take first bit as the sign, and the remaining bits as integers
signs_nums = [(-1 if bits[0] == '0' else 1, int(bits[1:], 2)) 
                  for bits in bits_list]
# use modulo to ensure that the numbers fall within the require interval:
#   -2.048 ≤ x ≤ 2.048
x = [sign * (num % 2.048) for sign, num in signs_nums]
瑞克凯格斯

bits_list = split_string_into_chunks(编码,n)

这行代码调用了一个函数 split_string_into_chunks,有 2 个参数,你没有显示它们是什么。bits_list 是看起来像数据帧列表或字典对象的返回值

sign_nums = [(-1 if bits[0] == '0' else 1, int(bits[1:], 2)) 对于 bits_list 中的位]

方括号的使用告诉我这就是所谓的列表理解。为此,我总是从行尾开始。

for bits in bits_list - This part of the line says I have a list of values and the for loop will process each element of the list via the variable 'bits'.

-1 if bits[0] == '0' - This if statement is a little backwards. what is saying is I will return the number -1 if the first value of bits is equal to 0. From this statement, it apprears that bits is actually a value pair listing which means that bits_list is probably a python dict object.

else 1 - this is the else part of the if above if statement. So if the value of bits[0] is not equal to 0 then I will return 1.

int(bits[1:], 2) - This part is interesting as it converts the bits[1:] to binary.

sign_nums - this is the returned list of binary values based 

x = [sign * (num % 2.048) for sign, num insigns_nums]

这再次使用列表理解。有了这个结构,我发现从右边开始向左移动更容易。所以分解它;

sign_nums - is a python dictionary or two-dimensional array object which the for loop will loop over.
num - is an individual value from the sign_nums dictionary object.
sign - is the second element from the sings_num dictionary that is associated with num.
The for loop will pull out individual value pair items from signs_nums.

sign * (num % 2.048) the first part in brackets takes the modulus of num divided by 2.048 and then multiplies that by whatever is in sign
x - this is the returned list from the line of code, which happens to be the answer to the sum sign * (num % 2.048).

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章