Reputation: 434
I'm trying to divide a list, according to user input. for example, I can get a list of
(["A","B","C","D"],num_of_groups)
>>>["AB","BC","CD","DA"]
my problem is with the last element. because like in the example, I need to take the last and first elements in a list (could be also last two and first three .. )
I tried doing so by adding all the element twice and then slicing, but then I have a problem that when the user wants a group of all elements, I'm returning two groups of the elements instead of only the one. I'll explain:
this is what I'm doing
list_copy = list(char_list)*2
#get the slice in the size of n.
slices.append(list_copy[i:i+n])
this is what happaning when user eners a size same as the list size
(["A","B","C"],3)
>>>["ABC","ACB","BAC","BCA","CAB","CBA","ABC","ACB","BAC","BCA","CAB","CBA"]
*instead of ["ABC","ACB","BAC","BCA","CAB","CBA"]
is there any other way of doing so? I would love some help! thanks!
Upvotes: 0
Views: 116
Reputation: 2053
It's a little ambiguous as to what you're trying to achieve. In your first example, you wrap around to get DA
, however in your last example you only want ['ABC']
and not perform the same wrapping to get ['ABC', 'BCA', 'CAB']
?
If you're looking to get the wrapping effect, then here's something you can do:
from itertools import islice, cycle
def group(l, size):
return [ ''.join(islice(cycle(l), i, i + size)) for i in xrange(len(l)) ]
Using itertools.cycle is a little more convenient than doubling the list. Since you're working off an iterator instead of a list, you have to pair it up with itertools.islice to do the slicing.
Here's the example output:
>>> group(['A', 'B', 'C', 'D'], 2)
['AB', 'BC', 'CD', 'DA']
>>> group(['A', 'B', 'C'], 1)
['A', 'B', 'C']
>>> group(['A', 'B', 'C'], 2)
['AB', 'BC', 'CA']
>>> group(['A', 'B', 'C'], 3)
['ABC', 'BCA', 'CAB']
>>> group(['A', 'B', 'C'], 4)
['ABCA', 'BCAB', 'CABC']
Upvotes: 0
Reputation: 5515
using the wonderful power of zip
:
>>> l = ["A","B","C","D"]
>>> for i in zip(l,l[1:]+l[:1]): print(''.join(i))
AB
BC
CD
DA
This may be confusing but what is essentially happening is iterating through 2 lists, your original one and a copy of your original where the each element is moved over one. You could also use this for a list comprehension:
>>> [''.join(i) for i in zip(l,l[1:]+l[:1])]
['AB', 'BC', 'CD', 'DA']
Upvotes: 0
Reputation: 49318
Use the modulus operator %
to start at the beginning when necessary:
>>> l = ['a', 'b', 'c', 'd']
>>> [l[i%len(l)]+l[(i+1)%len(l)] for i in range(len(l))]
['ab', 'bc', 'cd', 'da']
>>> [l[i%len(l)]+l[(i+1)%len(l)] for i in range(2*len(l))]
['ab', 'bc', 'cd', 'da', 'ab', 'bc', 'cd', 'da']
Upvotes: 2