Printing a tuple in Python with user-defined precision - python

Following Printing tuple with string formatting in Python, I'd like to print the following tuple:
tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
with only 5 digits of precision. How can I achieve this?
(I've tried print("%.5f" % (tup,)) but I get a TypeError: not all arguments converted during string formatting).

You can print the floats with custom precision "like a tuple":
>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> print('(' + ', '.join(('%.5f' % f) for f in tup) + ')')
(0.00390, 0.39024, -0.00585, -0.58537)

Possible workaround:
tup = (0.0039024390243902443, 0.3902439024390244, -
0.005853658536585366, -0.5853658536585366)
print [float("{0:.5f}".format(v)) for v in tup]

try the following (list comprehension)
['%.5f'% t for t in tup]

Try this:
class showlikethis(float):
def __repr__(self):
return "%0.5f" % self
tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
tup = map(showlikethis, tup)
print tup
You may like to re-quote your question, tuple dnt have precision.

You can iterate over tuple like this, and than you can print result
for python > 3
["{:.5f}".format(i) for i in tup]
And for python 2.7
['%.5f'% t for t in tup]

Most Pythonic way to achieve this is with map() and lambda() function.
>>> map(lambda x: "%.5f" % x, tup)
['0.00390', '0.39024', '-0.00585', '-0.58537']

I figured out another workaround using Numpy:
import numpy as np
np.set_printoptions(precision=5)
print(np.array(tup))
which yields the following output:
[ 0.0039 0.39024 -0.00585 -0.58537]

Here's a convenient function for python >3.6 to handle everything for you:
def tuple_float_to_str(t, precision=4, sep=', '):
return '({})'.format(sep.join(f'{x:.{precision}f}' for x in t))
Usage:
>>> print(funcs.tuple_float_to_str((12.3456789, 8), precision=4))
(12.3457, 8.0000)

you can work on single item.
Try this:
>>> tup = (0.0039024390243902443, 0.3902439024390244, -0.005853658536585366, -0.5853658536585366)
>>> for t in tup:
print ("%.5f" %(t))
0.00390
0.39024
-0.00585
-0.58537

Related

Convert from tuple to string, untuplify

def untuplify(tpl):
return map(lambda x: str(x), tpl)
I can't get the output for untuplify((1, 2, 3, 4, 5)) which is 12345
Use str.join():
>>> def untuplify(tpl):
... return "".join(map(str, tpl))
...
>>> untuplify((1,2,3,4))
'1234'
>>>
The reason you're getting unexpected output is because map() returns a list. str.join() is the canonical way of joining strings from a sequence into a single string.

How do you apply a list of lambda functions to a single element using an iterator?

I want to apply a list of lambda functions to a single element using an iterable that has to be created with yield.
The list of lambda functions would have something like:
[<function <lambda> at 0x1d310c8>, <function <lambda> at 0x1d355f0>]
And I want to apply every function, from left to right , to a single element using yield to construct an iterable to iterate the list
def apply_all(functions, item):
for f in functions:
yield f(item)
Example usage:
functions = [type, id, hex]
for result in apply_all(functions, 55):
print result
gives
<type 'int'>
20326112
0x37
Give this a shot:
def lambda_apply(unnamed_funcs, element):
for unnamed in unnamed_funcs:
yield unnamed(element)
>>> l = [lambda x: x**2, lambda x: 2*x]
>>> el = 5
>>> for y in lambda_apply(l, el):
... print y
...
25
10
Note that this works not only for a list of unnamed functions, but any list of functions of arity 1. This is because all functions, named or not, are first class objects in python. You can store them in a list, and use them later, as demonstrated above.
The answer could be formulated as
import numpy as np
def apply_funcs( funcs, val ):
for func in funcs:
yield func(val)
my_funcs = [lambda x: np.cos(x), np.sin, np.tan]
my_val = 0.1
for res in apply_funcs( my_funcs, my_val ):
print res
where the apply_funcs function does the trick and the rest is just for demonstration purposes.
Do you necessarily need a yield statement?
Because there is another way to create generator: to use ().
applied_it = (f(item) for f in functions)
def apply(value, lambda_list):
for function in lambda_list:
yield (function(value))

what is this saying in python

map(tuple, map(lambda row: [float(row[0]), int(row[1]), parse(row[2])], res))
Can someone help me with the syntax here? I'm trying to understand specifically what tuple and lambda is referring to.
If it's easier to follow you could rewrite this a few times, from
map(tuple, map(lambda row:
[float(row[0]), int(row[1]), parse(row[2])], res))
to
map(lambda row: (float(row[0]), int(row[1]), parse(row[2])), res)
to
[(float(row[0]), int(row[1]), parse(row[2])) for row in res]
That doesn't really answer your question, but I thought it was easier to read ;)
tuple() is a constructor for a "tuple" object, that can convert a list (or other sequence object) to a tuple.
For example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> tuple(a)
(1, 2, 3)
When used in your example, it converts the result of each lambda expression from a list to a tuple. It seems a bit redundant, because the following should be equivalent:
map(lambda row: (float(row[0], int(row[1], parse(row[2])), res)
Note the use of () parentheses instead of [] square brackets which creates a tuple rather than a list.

Python: how to create a function pointer with a set argument?

My problem:
Given the following:
def foo(a,b)
I am trying to call the python 'map' function while passing in a list for 'a' but use a set value for 'b.'
Another relevant fact is that 'b' is user input and thus, I cannot use the syntax:
def foo(a,b='default value')
I want my 'map' call to look like this:
map(foo_wrapper,list_for_a)
where 'foo_wrapper' is some function that takes in 'a' but uses the user specified 'b.'
I don't know whether function pointers can be specified this way and suspect that they cannot.
My solution to this problem uses globals, so if there's a more elegant way and the above is impossible, I will mark that as the answer as well.
Here is my solution in a nutshell:
b = ''
def foo(a,b):
print b,a
def foo_wrapper(a):
foo(a,b)
def main():
if sys.argv[1]:
a = ['John', 'Jacob', 'Jingle all the way']
global b
b = sys.argv[1]
map(foo_wrapper,a)
There may be a typo or two in the above; I am simplifying the problem from what I actually need to do.
Thanks for the replies!
You can use functools.partial() for this purpose:
from functools import partial
def f(a, b):
return a + b
x = range(10)
print map(partial(f, b=3), x)
prints
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
You want something akin to currying. You can just use lambda here:
map(lambda x: f(x,3), a)
Use a list comprehension or a generator expression
[f(x, your_set) for x in your_list]
If you don't need a list as a result, but just a lazy evaluated iterator, you can use a generator expression (or if you meant Python 3's map).
(f(x, your_set) for x in your_list)
Edit:
For your functions that would be:
L = ['John', 'Jacob', 'Jingle all the way']
[foo(a, b=b) for a in L]
List comprehensions are a syntax sugar to replace uses of map with lambda. If you have one of the following:
L2 = map(lambda arg: f(arg) + arg, L1)
L2 = map(lambda (x,y): x + y, L1)
L2 = map(lambda <arg>: <expression>, L1)
They can be rewritten as list comprehensions:
L2 = [f(arg) + arg for arg in L1]
L2 = [x + y for x, y in L1]
L2 = [<expression> for <arg> in L1]
Generator expressions are similar, but instead of a list they return a lazy iterator, and are written with parens instead of square brackets. (And because map in Python 3 is changed to not return lists, there its equivalent is a generator expression.) Sometimes a list is not need, for example when you want to do:
','.join(map(lambda x: x.upper(), L))
The equivalent list comprehension is:
','.join([x.upper() for x in L])
But you actually don't need a list, so you can simply do:
','.join(x.upper() for x in L)

Python: Nested Loop

Consider this:
>>> a = [("one","two"), ("bad","good")]
>>> for i in a:
... for x in i:
... print x
...
one
two
bad
good
How can I write this code, but using a syntax like:
for i in a:
print [x for x in i]
Obviously, This does not work, it prints:
['one', 'two']
['bad', 'good']
I want the same output. Can it be done?
List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing
from __future__ import print_function
for x in a:
[print(each) for each in x]
doing so is amazingly unpythonic, and results in the generation of a list that you don't actually need. The best thing you could do would simply be to write the nested for loops in your original example.
Given your example you could do something like this:
a = [("one","two"), ("bad","good")]
for x in sum(map(list, a), []):
print x
This can, however, become quite slow once the list gets big.
The better way to do it would be like Tim Pietzcker suggested:
from itertools import chain
for x in chain(*a):
print x
Using the star notation, *a, allows you to have n tuples in your list.
>>> a = [("one","two"), ("bad","good")]
>>> print "\n".join(j for i in a for j in i)
one
two
bad
good
>>> for i in a:
... print "\n".join(i)
...
one
two
bad
good
import itertools
for item in itertools.chain(("one","two"), ("bad","good")):
print item
will produce the desired output with just one for loop.
The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:
from __future__ import print_function
for x in a:
print(*x, sep="\n")
Simply use * to unpack the list x as arguments to the function, and use newline separators.
You'll need to define your own print method (or import __future__.print_function)
def pp(x): print x
for i in a:
_ = [pp(x) for x in i]
Note the _ is used to indicate that the returned list is to be ignored.
This code is straightforward and simpler than other solutions here:
for i in a:
print '\n'.join([x for x in i])
Not the best, but:
for i in a:
some_function([x for x in i])
def some_function(args):
for o in args:
print o

Categories