Transform two tuples item by item

G

Gnarlodious

What is the best way to operate on a tuple of values transforming them against a tuple of operations? Result can be a list or tuple:

tup=(35, '34', 0, 1, 31, 0, '既濟')

from cgi import escape
[tup[0], "<span class='H'>{}</span>".format(tup[1]), bool(tup[2]), bool(tup[3]), tup[4], bool(tup[5]), escape(tup[6])]

-> [35, "<span class='H'>34</span>", False, True, 31, False, '&amp;#26082;&amp;#28639;']

But I want to loop rather than subscripting.

-- Gnarlie
 
T

Tim Chase

What is the best way to operate on a tuple of values
transforming them against a tuple of operations? Result can be
a list or tuple:

tup=(35, '34', 0, 1, 31, 0, '既濟')

from cgi import escape
[tup[0], "<span> class='H'>{}</span>".format(tup[1]), bool(tup[2]),
bool(tup[3]), tup[4], bool(tup[5]), escape(tup[6])]

-> [35, "<span class='H'>34</span>", False, True, 31, False,
'&amp;#26082;&amp;#28639;']

But I want to loop rather than subscripting.

Well, you can do something like
from cgi import escape
nop = lambda x: x
tup = (35, '34', 0, 1, 31, 0, '既濟')
ops = [nop, "<span class='H'>{0}</span>".format, bool, bool, nop, bool, escape]
[f(x) for f, x in zip(ops,tup)]
[35, "<span class='H'>34</span>", False, True, 31, False,
'&amp;#26082;&amp;#28639;']

Note #1: I had to change your format from "{}" to "{0}", at least
in 2.6 I've got here)

Note #2: it's spelled ".format" not ".format()" which puts the
function reference in the "ops" list, not the results of calling it.

-tkc
 
S

Steven D'Aprano

What is the best way to operate on a tuple of values transforming them
against a tuple of operations? Result can be a list or tuple:

Create a list of functions:

ops = [lambda obj: obj,
"<span class='H'>{}</span>".format,
bool,
bool,
lambda obj: obj,
bool,
escape,
]

then use zip to pair them up with their arguments:

results = [f(x) for f,x in zip(ops, tup)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top