Reputation: 13
I have a list:
L = [1, 2, 3, 4, 5, 6]
and I want to print
1 B 2 J 3 C 4 A 5 J 6 X
from that list.
How do I do that?
Do I have to make another list and zip
them up, or is there some way I can have the letters in my format specifier?
Upvotes: 0
Views: 208
Reputation: 11701
A nice way to do this is have a dictionary of numbers to prefixes:
prefixes = {1: 'B', 2: 'J', 3: 'C', 4: 'A', 5: 'J', 6: 'X'}
Then you can do:
print ' 'join('%s %s' % (num, prefix) for num, prefix in prefixes.itervalues())
If you also have a list of letters:
nums = [1, 2, 3, 4, 5, 6]
ltrs = ['B', 'J', 'C', 'A', 'J', 'X']
print ' '.join('%s %s' % (num, ltr) for num, ltr in zip(nums, ltrs)
Upvotes: 1
Reputation: 176750
You could do it either way:
L = [1, 2, 3, 4, 5, 6]
from itertools import chain
# new method
print "{} B {} J {} C {} A {} J {} X".format(*L)
# old method
print "%s B %s J %s C %s A %s J %s X" % tuple(L)
# without string formatting
print ' '.join(chain.from_iterable(zip(map(str, L), 'BJCAJX')))
See the docs on str.format and string formatting.
Upvotes: 2