PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How do I get values from for loop in a list?

 May 13, 2022     append, list, python     No comments   

Issue

I am trying to print the output of the for loop given below in a list but I get the following results:

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)

Here, the output is :

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

But I want it to be:

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

I have tried using

print(','.join(dist)) 

but it says

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

How do I get the output I want?


Solution

First, move the dist initialization outside of the loop.

Then you must convert floating-point numbers to strings before joining them, either in the loop:

dist.append(str(cos_dist))

Or after the loop:

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

Overall, list comprehension is a better tool for list construction:

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


Answered By - DYZ
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing