Python 3.x Python-UnboundLocalError:赋值前引用了局部变量“d”

Python 3.x Python-UnboundLocalError:赋值前引用了局部变量“d”,python-3.x,Python 3.x,此功能: def weighted_choice(self, dna): """ Chooses a random element from tags. Weight determines the probability of choosing its respective item. """ weight_total = sum((d[1] for d in dna)) n = random.uniform(0, weight_

此功能:

def weighted_choice(self, dna):

    """
    Chooses a random element from tags.
    Weight determines the probability 
    of choosing its respective item. 
    """

    weight_total = sum((d[1] for d in dna))

    n = random.uniform(0, weight_total)

    for d, weight in dna:
        if n < weight:
            return d
        n = n - weight

    return d
数据结构:

追踪之后:

def crossover(self, dna1, dna2):

        """
        Mixes dna1 and dna2.
        """

        global breed
        # get alleles for gene 1
        A = self.alleles(dna1)[1]
        a = self.alleles(dna1)[2]
        # get alleles for gene 2
        B = self.alleles(dna2)[1]
        b = self.alleles(dna2)[2]
        # format alleles as dictionaries
        AB, Ab, Ba, ab = ({} for i in range(4))
        # genre 1
        AB[str(self.weighted_choice(A))]='A'
        AB[str(self.weighted_choice(B))]='B'
        # genre 2
        Ab[str(self.weighted_choice(A))]='A'
        Ab[str(self.weighted_choice(b))]='b'
        # genre 3
        Ba[str(self.weighted_choice(B))]='B'
        Ba[str(self.weighted_choice(a))]='a'
        # genre 4
        ab[str(self.weighted_choice(a))]='a' 
        ab[str(self.weighted_choice(b))]='b'

        # pick a random number
        x = random.random()
        # set percentage
        if x < 0.25:
            # if low, generate recessive genotypes
            genotype = random.choice([ab])
            breed = ' '.join([k for k in genotype])
            #return genotype
        else:
            # if low, generate dominant genotypes
            genotype = random.choice([AB, Ab, Ba])
            breed = ' '.join([k for k in genotype])


        return (genotype, breed)




def fitness(self, dna1, dna2, generations=600):

        '''
        Most adapted phenotype after many generations.
        '''

        # container for unique breeds
        offspring = set()
        # fetch million song dataset 
        pool = self.genome()
        # test for many generations
        for generation in range(generations):
            print ("Generation %s..." % (generation))
            # mix phenotype
            breed = self.crossover(dna1,dna2)[1]
            # print each offspring
            print (breed)
            # build genotype
            offspring.add(breed)


        # container for sequences
        matches = []
        # lookup offspring in genetic pool
        for o in sorted(offspring):
            for p in pool:
                # compare genetic sequences
                seq = difflib.SequenceMatcher(None, a=o.lower(), b=p.lower())
                print (o, p, round(seq.ratio(), 4))
                # sort matches by similarity ratio
                matches.append([o, p, round(seq.ratio(), 4)])

        # order fittest by descending order
        # similarity = sorted(matches, key=lambda x: x[2], reverse=True)
        similarity = sorted(matches, key=lambda x: x[2], reverse=True)

        # containers for optimized genetic values
        fit = []
        # add
        for m in matches:
            # if m[2] == 1.0:
            #   fit.append(m)
            if 0.8880 <= m[2] <= 1.0:
                fit.append(m)

        return sorted(fit, key=lambda x: x[2], reverse=True)


def alleles(self, dna):

        global allele
        # each user is one
        individual = dna.keys()
        # containers for data
        total = []
        dominant = []
        recessive = []

        for k, v in dna.items():
            # track gene strength # python 3 requires list for indexing
            weight = list(v.values())
            # add all weights 
            total.append(weight[0])
            # each tag is a 'gene'
            gene = v.keys()
            # format in allele fashion
            allele = zip(gene, weight)
            # get the average weight for tags
            mean = sum(total)/len(total)
            # print allel
            for a in allele:
                # above avg is a dominant tag
                if a[1] > mean:
                    dominant.append(a)
                elif a[1] == 1.0:
                    dominant.append(a)
                    recessive.append(a)
                # below avg is a recessive tag
                else:
                    recessive.append(a)


        return (individual, dominant, recessive)

有什么问题吗?

以此为例:

>>> def f(a):
...     for d in a:
...         if d % 2 == 0:
...             return d
...     return d  # You're returning d, but if the list is empty d is expected to be undefined
... 
>>> f([5])
5
>>> f([5, 5, 2])
2
>>> f([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
UnboundLocalError: local variable 'd' referenced before assignment
如果dna为空,请避免调用加权_选项 编辑:

首先,你要为每个dna1和dna2调用两次等位基因方法

我要改变这个:

A = self.alleles(dna1)[1]
a = self.alleles(dna1)[2]

B = self.alleles(dna2)[1]   
b = self.alleles(dna2)[2]
致:

注:

只有两个调用和元组扩展才能实现这个技巧。它将返回的单个、显性和隐性值分配给正确的变量。 曾经说过,显性或隐性都是空的。错误本身必须在你的等位基因方法中

    def alleles(self, dna):
        # Your code goes here. Make sure it does what you're expecting.
        # And if dominant and/or recessive are not expected to be empty
        # with the given input (aka. dna) you have to fix this method.

        print('dominant:', dominant)    
        print('recessive:', recessive)

        return (individual, dominant, recessive)

你没有提到dna对象是什么类型的

1.假设dna是dict,用方法项迭代dict

for d, weight in dna.items():
    if n < weight:
        return d
    n = n - weight

return d
2.如果dna是列表、元组或集合,则使用枚举方法对其进行迭代

for d, weight in enumerate(dna):
    if n < weight:
        return d
    n = n - weight

return d

右边的术语是d,未定义,意思是它不存在。空意味着它存在,但它没有。我用工作示例和数据结构编辑了Rizwan教授,我在编辑你的答案时搞砸了一点你没有包括一个重要的def等位基因。dna1和dna2看起来不错,但不知何故,这些等位基因为一个或所有A、A、B和B变量返回了一个空迭代器。尝试打印出值:打印“这是A”,A,打印“这是A”,A,打印“这是b”,b,打印“这是b”,b,直到找到空值one@slackmart我添加了等位基因。看看是否有帮助,非常感谢
A = self.alleles(dna1)[1]
a = self.alleles(dna1)[2]

B = self.alleles(dna2)[1]   
b = self.alleles(dna2)[2]
# It seems like you only care about 2nd and 3rd elements being
# returned, so _ will silently take the `individual` value
_, A, a = self.alleles(dna1)
_, B, b = self.alleles(dna2)
    def alleles(self, dna):
        # Your code goes here. Make sure it does what you're expecting.
        # And if dominant and/or recessive are not expected to be empty
        # with the given input (aka. dna) you have to fix this method.

        print('dominant:', dominant)    
        print('recessive:', recessive)

        return (individual, dominant, recessive)
for d, weight in dna.items():
    if n < weight:
        return d
    n = n - weight

return d
for d, weight in enumerate(dna):
    if n < weight:
        return d
    n = n - weight

return d