【问题标题】:Accessing values of a tuple inside a list访问列表中元组的值
【发布时间】:2020-12-29 18:45:25
【问题描述】:

我是初学者。我有一个问题,我们如何访问列表中元组的值。示例

def point_function():
    my_list=[]
    num=int(input("Dear User, How many points you want to enter: "))
    for i in range(1,num+1):
        print(f"Please input the coordinates of the point {i}")
        x=float(input("Please enter x-coordinate of the point: "))
        y=float(input("Please enter y-coordinate of the point: "))
        my_tuple=(x,y)
        my_list.append(my_tuple)
    print(my_list)                    

point_function()

这个函数将创建一个存储点坐标的元组列表,现在如果我想访问它们并找到所有点之间的距离。覆盖点和其后点之间的距离。我该怎么做?

我试图搜索它,但我没有得到任何合适的答案。 提前感谢您的回答。

【问题讨论】:

  • 我认为您已经接受了错误(且未格式化)的答案(它仅 打印 第一个元素,即 x 和 y 坐标列表中的 x 坐标,即完全错误)。请不要接受错误的答案。

标签: python list tuples


【解决方案1】:

你可以这样访问它:

for tup in my_list:
    x, y = tup # assuming there two values inside the tuple to unpack
    print(x, y)
    print(tup[0], tup[1]) # in case you want to access with indexing

从列表中的第二个元组中减去第一个元组:

x_diff = my_list[0][0] - my_list[1][0]
y_diff = my_list[0][1] - my_list[1][1]

【讨论】:

  • 很抱歉再次打扰您,正如上面我的问题中提到的计算点之间的距离,我必须用第二个元组的第一个值减去第一个元组的第一个值,同样如此为第二个值。应该怎么做才能减去它们?
【解决方案2】:

更改 print(my_list) 以返回 my_list 在主代码块中分配你的 def 函数 (points = point_function()),然后你可以打印出结果。您可以使用 for 循环整理 x 和 y 值。我不知道计算点之间距离的公式,但我认为你可以解决这个问题。

【讨论】:

    【解决方案3】:
    tuple_list = [('a', 'b'), ('c', 'd')]
    first_element = []
    
    for i in tuple_list:
       first_element.append(i[0])
    
    print(first_element)
    

    输出

    'a', 'c'
    

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 2021-05-29
      • 1970-01-01
      • 2015-02-04
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多