【问题标题】:How do I get values from for loop in a list?如何从列表中的 for 循环中获取值?
【发布时间】:2021-07-29 06:06:55
【问题描述】:

我正在尝试在列表中打印下面给出的 for 循环的输出,但得到以下结果:

import math
S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
p,q = 3,-4
dist = []
for x,y in S:
    dist=[]
    cos_dist = math.acos((x*p + y*q)/((math.sqrt(x**2 + y**2))*(math.sqrt(p**2 + q**2))))
    dist.append(cos_dist)
    print(dist)

这里的输出是:

[2.0344439357957027]
[1.8545904360032246]
[2.9996955989856287]
[0.06512516333438509]
[2.498091544796509]
[1.2021004241368467]
[1.4288992721907328]
[0.9272952180016123]
[0.14189705460416438]

但我希望它是:

 [2.0344439357957027,1.8545904360032246,2.9996955989856287,0.06512516333438509,2.498091544796509,1.2021004241368467,1.4288992721907328,0.9272952180016123,0.14189705460416438]

我尝试过使用

print(','.join(dist)) 

但它说

TypeError: sequence item 0: expected str instance, float found

如何获得我想要的输出?

【问题讨论】:

  • 您在循环内再次重新分配dist。每次,前一个列表都会被丢弃。所以你只得到1个元素。从循环中删除dist=[]

标签: python list append


【解决方案1】:

首先,将dist 初始化移出循环。

然后您必须在加入它们之前将浮点数转换为字符串,或者在循环中:

dist.append(str(cos_dist))

或者在循环之后:

print(','.join(map(str, dist)) )

总的来说,列表推导是构建列表的更好工具:

dist = [math.acos((x*p + y*q) / ((math.sqrt(x**2 + y**2))\
                      *(math.sqrt(p**2 + q**2)))) for x,y in S]

【讨论】:

    【解决方案2】:

    试试这个:

    import math
    S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
    p,q = 3,-4
    dist = []
    for x,y in S:
        cos_dist = math.acos((x*p + y*q)/((math.sqrt(x**2 + y**2))*(math.sqrt(p**2 + q**2))))
        dist.append(cos_dist)
    print(dist)
    

    第 1 点,您的列表声明应该在 for 循环之外,否则您将只有列表中的最新元素。第 2 点,您应该在循环之外打印以打印预期输出中显示的所有元素。这会做的事情,不需要 ','.join().

    如果您想使用连接,请使用

    print('[' + ','.join(map(str, dist)) + ']')
    

    这将给出相同的结果。

    【讨论】:

      【解决方案3】:

      如果你仔细观察:

      for x,y in S:
          dist=[]
      

      您每次都在分配dist=[]。因此,每次迭代都会丢弃以前的值,并创建一个名为dist 的新空白列表。这就是为什么,你只会得到 1 个元素。

      相反,删除您定义列表的行。另外,把print(dist)移到外面

      import math
      S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
      p,q = 3,-4
      dist = []
      for x,y in S:
          
          cos_dist = math.acos((x*p + y*q)/((math.sqrt(x**2 + y**2))*(math.sqrt(p**2 + q**2))))
          dist.append(cos_dist)
      print(dist)
      

      另一种选择:

      dist=[math.acos((x*p + y*q)/((math.sqrt(x**2 + y**2))*(math.sqrt(p**2 + q**2)))) for x,y in S]
      

      【讨论】:

      • 上面的代码很有帮助,它打印了一个列表中的数字。带有“cos_dist =”部分的列表理解显示无效的语法错误,因为可能是“=”符号,所以我猜最好不要使用“cos_dist”变量。
      • 另外,有没有办法可以显示“dist”的哪个值对应于“S”中的各个点?
      • @AzizAhmed,我没听明白吗?
      • 'dist' 中的值是 S 中坐标的余弦距离。现在我已经打印了像 '[2.0344439357957027,1.8545904360032246....]' 这样的距离,我可以打印它们属于哪些点喜欢'(1,2),(3,4)..'?
      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2017-09-17
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多