问题
I have a list of tuples like so (the strings are fillers... my actual code has unknown values for these):
list = [
('one', 'two', 'one'),
('one', 'two', 'one', 'two', 'one'),
('one', 'two', 'one', 'two', 'one', 'two', 'one'...)
]
I would like to wrap every other string (in this example, the 'two' strings) in <strong> </strong>
tags. It's frustrating that I can't do '<strong>'.join(list)
because every other one won't have the /. This is the only approach I can think of but the use of the flag bothers me... and I can't seem to find anything else on the google machine about this problem.
def addStrongs(tuple):
flag = False
return_string = ""
for string in tuple:
if flag :
return_string += "<strong>"
return_string += string
if flag :
return_string += "</strong>"
flag = not flag
return return_string
formatted_list = map(addStrongs, list)
I apologize if this is buggy, I'm still new to python. Is there a better way to do this? I feel like this could be useful in other areas too like adding in left/right quotes.
回答1:
>>> tuple = ('one', 'two', 'one', 'two', 'one')
>>> ['<strong>%s</strong>' % tuple[i] if i%2 else tuple[i] for i in range(len(tuple))]
['one', '<strong>two</strong>', 'one', '<strong>two</strong>', 'one']
回答2:
from itertools import cycle
xs = ('one', 'two', 'one', 'two', 'one')
print [t % x for x, t in zip(xs, cycle(['<strong>%s</strong>', '%s']))]
Using cycle
you can apply to more complex patterns than "every other".
回答3:
Slightly more Pythonic than unbeli's answer:
item = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % elem if i % 2 else elem for i, elem in enumerate(item)]
回答4:
@jhibberd's answer is fine, but just in case, here the same idea without imports:
a = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
formats = ['%s', '<strong>%s</strong>']
print [formats[n % len(formats)] % s for n, s in enumerate(a)]
回答5:
You can use enumerate
too. To me it just look cleaner.
tuple = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % x if i%2 else x for i, x in enumerate(tuple)]
来源:https://stackoverflow.com/questions/10271345/easily-alternate-delimiters-in-a-join