This

cond1=[Word(['AB', 'AC', 'AD', 'BC', 'BD', 'CD'])[i] for i in range(len(cond))]


gives ['AB', 'AC', 'AD', 'BC', 'BD', 'CD'] but I want that [r'$A-B$', r'$A-C$', r'$A-D$', r'$B-C$', r'$B-D$', r'$C-D$'] to make a header for a table. Is there a way to obtain what I expect ?

edit retag close merge delete

Sort by » oldest newest most voted

First a remark: in addition to iteration by index, Python offers iteration by values.

Since it makes code much more natural and readable, using it is encouraged.

For instance, if things is a list, and f is a function, then among the following two equivalent lines,

sage: [f(v) for v in things]
sage: [f(things[i]) for i in range(len(things))]


we can hopefully agree the first one is not only more concise but clearer.

This might do what you want.

ww = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
cond1 = ['${}-{}$'.format(*w) for w in ww]


With two {} placeholders in the string ${}-{}$', theformat method expects two arguments.

This works:

sage: '${}-{}$'.format('A', 'B')
'$A-B$


But if we provide the two arguments in packed form, e.g. as a list, tuple, or string, we need to unpack them.

This is done with * which used as a prefix is the unpacking operator in Python.

sage: w = ['A', 'B']
sage: '${}-{}$'.format(w)  # index error
sage: '${}-{}$'.format(*w)  # good
'$A-B$

sage: w = 'AB'
sage: '${}-{}$'.format(w)  # index error
sage: '${}-{}$'.format(*w)  # good
'$A-B$
`
more