简体   繁体   中英

Python Plot Regression

My ultimate goal is write a function that will take a list as a parameter and find the best fit line for the points in the list and then draw the points and the best fit line but I need some advice on what to do with my given list-

My parameter/list may be something like this: [(1,3),(5,8),(2,4)] I need to find the mean of the x values and the y values- I'm not sure how to separate my (x,y) points into one list of x values and one list of y values so I can find the mean of both separately. Maybe my idea to separate the coordinates isn't the most efficient idea...

Use zip :

>>> zip(*[(1,3),(5,8),(2,4)])
<zip object at 0x7f377bebe050>
>>> list(_)
[(1, 5, 2), (3, 8, 4)]
>>> xpoints, ypoints = zip(*[(1,3),(5,8),(2,4)])
>>> xpoints
(1, 5, 2)
>>> ypoints
(3, 8, 4)

Give a list of tuples, creating lists of the first and second elements in the tuple can be done with a list comprehension, as follows:

>>> z = [(1,3),(5,8),(2,4)]
>>> [a for a,b in z]
[1, 5, 2]
>>> [b for a,b in z]
[3, 8, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM