Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 创建包含三个元素的python列表_Python 3.x - Fatal编程技术网

Python 3.x 创建包含三个元素的python列表

Python 3.x 创建包含三个元素的python列表,python-3.x,Python 3.x,是否可以创建一个包含3个元素的列表 我想为精确的元素(三维坐标)创建一个列表(或者可能是元组)。 我可以这样做: nhat=input("Enter coordinate\n") 问题是它需要任何数字(甚至大于或小于3)。 但如果它是的话,我会让它提示输入数字,这将是一件好事。您可以尝试以下方法: def get_coords(): while True: s = input("Enter coordinates (x y z): ") try:

是否可以创建一个包含3个元素的列表

我想为精确的元素(三维坐标)创建一个列表(或者可能是元组)。 我可以这样做:

nhat=input("Enter coordinate\n")
问题是它需要任何数字(甚至大于或小于3)。
但如果它是的话,我会让它提示输入数字,这将是一件好事。您可以尝试以下方法:

def get_coords():
    while True:
        s = input("Enter coordinates (x y z): ")
        try:
            x, y, z = map(float, s.split())
        except ValueError: # wrong number or can't be floats
            print("Invalid input format.")
        else:
            return x, y, z
现在,您的代码变成:

nhatx, nhaty, nhatz = get_coords() # unpack tuple


所以输入应该是3或更多?输入的数量应该是3,准确地说…即
len(nhat)=3
exactSo请在创建列表之前检查长度,如果错误,请打印错误消息。
nhatx, nhaty, nhatz = get_coords() # unpack tuple
nhat = get_coords() # leave coords in tuple