语法错误:无法分配给运算符 [英] SyntaxError: cannot assign to operator

查看:71
本文介绍了语法错误:无法分配给运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def RandomString (length,distribution):
    string = ""
    for t in distribution:
        ((t[1])/length) * t[1] += string
    return shuffle (string)

这会返回标题中描述的语法错误.在这个例子中,distribution 是一个元组列表,每个元组包含一个字母和它的分布,列表中的所有分布加起来为 100,例如:

This returns a syntax error as described in the title. In this example, distribution is a list of tuples, with each tuple containing a letter, and its distribution, with all the distributions from the list adding up to 100, for example:

[("a",50),("b",20),("c",30)] 

length 是你想要的字符串的长度.

And length is the length of the string that you want.

推荐答案

Python 感到不安,因为您试图为无法赋值的内容赋值.

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

当您使用赋值运算符时,您将右侧的值赋给左侧的变量或元素.在您的情况下,左侧没有变量或元素,而是一个解释值:您试图为不是容器"的东西分配一个值.

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

根据您所写的内容,您只是误解了此运算符的工作方式.像这样切换你的操作数.

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

请注意,我已将分配的值包装在 str 中,以便将其转换为 str 以便它与 string 兼容> 它被分配给的变量.(数字和字符串不能相加.)

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

这篇关于语法错误:无法分配给运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆