我正在尝试理解以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]
答案 0 :(得分:1)
bits_list = split_string_into_chunks(coding,n)
此代码行调用一个函数split_string_into_chunks,它带有2个参数,这些参数是您不显示的。 bits_list是返回值,看起来像数据框列表或字典对象
signs_nums = [(如果bits [0] =='0',则为-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 = [符号*(数字*(num%2.048),数字以signs_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).