在命令行上输入元组并将其分配给元组

input of a tuple on the command line and assigning it to a tuple

我想输入成对的坐标(点)来定义一条线(向量),并想做类似的事情:

var = raw_input("Input LineA (x1,y1,x2,y2) ")

lineA[0][0]=var[0]
lineA[1][0]=var[1]
lineA[0][1]=var[2]
lineA[1][1]=var[3]
print lineA

lineA 应该作为元组的元组使用,la:

lineA = ((2.5,2.0),(3.0,4.0))

有人知道如何优雅地解决这个问题吗?目前我得到

 Traceback (most recent call last):   File "win.py", line 34, in
 <module>
    lineA[0][0]=var[0] TypeError: 'tuple' object does not support item assignment

试试这个:

lineA = ((var[0], var[2]), (var[1], var[3]))

元组是不可变的,因此您不能为其单个元素(与列表相反)赋值。

@Edit1: 对不起,我没有注意第一行。这是一个更新:

raw_str = raw_input("Input LineA (x1,y1,x2,y2): ")
# Split the string by commas(this is the separator), raise Exception if we have more or less than 4 values.
tokens = raw_str.split(",")
if len(tokens) != 4:
    raise ValueError("Invalid input.")
# Now we eliminate any SPACEs, TABs, or ; that the user might have input and then convert everything to floats.
var = [item.strip(" \t;") for item in tokens]
lineA = ((float(var[0]), float(var[2])), (float(var[1]), float(var[3])))