Python 根据极性将数字设置为真或假的代码

Python code for setting a number to true or false depending on the polarity

我有一个列表

import sys
A=[[51,52,-53],[51,-52,53],[199,-200,203],[-200]]

我需要先检查是否有一个只有一个数字的子列表, 如果那是真的(在上述情况下是真的)我需要检查它的极性 如果它是正数,那么我必须将列表中所有相同的数字设置为 true,对于那些为负数的正数和 false

我的代码:

for i in A:
    if (len(i)==1):
        single=i[0]
        for j in i:
            if (j ==single):
                if (j>0):
                    j=True
                else:
                    j=False

print A

输出:

[[51, 52, -53], [51, -52, 53], [199, -200, 203], [-200]]

输出应该是

[[51, 52, -53], [51, -52, 53], [199, false, 203], [false]]

可能有更有效的方法来实现这一点。

def polarity (my_list):
    sub_list = ((i[0], True) if i[0]>-1 else (i[0], False) for i in my_list if len(i) == 1)

    for each in sub_list:
        for each_list in my_list:
            for ind, ele in enumerate(each_list):
                if ele == each[0]:
                    each_list[ind] = each[1]

    return my_list

A=[[51,52,-53],[51,-52,53],[199,-200,203],[-200]]
print(polarity(A))
B=[[51,52,-53],[51,-52,53],[199,-200,203],[-200],[52]]
print(polarity(B))    

结果:

[[51, 52, -53], [51, -52, 53], [199, False, 203], [False]]
[[51, True, -53], [51, -52, 53], [199, False, 203], [False], [True]]
def polarity (cnf):
sub_list = ((i[0], True) if i[0]>-1 else (i[0], False) for i in cnf if len(i) == 1)
for each in sub_list:
    for each_list in cnf:
        for ind, ele in enumerate(each_list):
            if ele == each[0]:
                each_list[ind] = each[1]
            elif ele == -each[0]:
                each_list[ind] = not each[1]
return cnf
A=[[51,52,-53],[51,-52,53],[199,-200,203],[200,203,200],[-200]]
print(polarity(A))
B=[[51,52,-53],[51,-52,53],[199,-200,203],[-52, 200],[-200],[52]]
print(polarity(B))

@TanveerAlam 非常感谢您的帮助。我只需要再添加 2 行即可找到解决方案。

结果:
[[51, 52, -53], [51, -52, 53], [199, 假, 203], [真, 203, 真], [假]]<br> [[51, 真, -53], [51, 假, 53], [199, 假, 203], [假, 真], [假], [真]]