Ask Your Question
0

From words to headers

asked 2021-01-05 17:09:28 +0200

Cyrille gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-01-05 21:36:30 +0200

slelievre gravatar image

updated 2021-01-06 03:50:28 +0200

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$
edit flag offensive delete link more

Comments

Thanks. Just a question what means the star.

Cyrille gravatar imageCyrille ( 2021-01-05 22:56:13 +0200 )edit

Edited to add explanation of star unpacking.

slelievre gravatar imageslelievre ( 2021-01-06 16:04:43 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-01-05 17:09:28 +0200

Seen: 110 times

Last updated: Jan 06 '21