The Recruit
The Recruit

Reputation: 863

Concatenating Arbitrary number of items of a string in Python

Given a list ['a','b','c','d','e','f'].No. of divisions to be made 2.. So In the first string i want to take the 0,2,4 elements of the list, and then concatenate them separated by a space delimiter with the second string of 1,3,5 elements. The output needs to be in the form of k = ["a c e", "b d f"]

The actual program is to take in a string (eg {ball,bat,doll,choclate,bat,kite}), also take in the input of the number of kids who take those gifts(eg 2), and then divide them so that the frst kid gets a gift, goes to the back of the line, the second kid takes the gift and stands at the back, in that way all kids take gifts. If gifts remain then the first kid again takes a gift and the cycle continues.... desired output for above eg: {"ball doll bat" , "bat choclate kite"}

Upvotes: 0

Views: 679

Answers (2)

mata
mata

Reputation: 69092

lst = ['a','b','c','d','e','f']

k = [" ".join(lst[::2]), " ".join(lst[1::2])]

output:

['a c e', 'b d f']

more generic solution:

def group(lst, n):
    return [" ".join(lst[i::n]) for i in xrange(n)]

lst = ['a','b','c','d','e','f']
print group(lst, 3)

output:

['a d', 'b e', 'c f']

Upvotes: 6

NPE
NPE

Reputation: 500963

Here is a general way to do this for any number of groups:

def merge(lst, ngroups):
    return [' '.join(lst[start::ngroups]) for start in xrange(ngroups)]

Here is how it's used:

>>> lst = ['a','b','c','d','e','f']
>>> merge(lst, 2)
['a c e', 'b d f']

>>> merge(lst, 3)
['a d', 'b e', 'c f']

Upvotes: 6

Related Questions