Reputation: 13
I'm trying to program the 'Card Trick' practice program for GCSE Computer Science but I'm stuck on one function.
I have an array which contains 3 other arrays, and I want to take the items within the 3 arrays and move them into another list.
This is the code which I have and I'm not sure why it doesn't work:
def remake_list(old_piles,mid_pile) :
print(old_piles)
newlist = []
if mid_pile == 1 :
newlist.extend(old_piles[1])
newlist.extend(old_piles[0])
newlist.extend(old_piles[2])
if mid_pile == 2 :
newlist.extend(old_piles[0])
newlist.extend(old_piles[1])
newlist.extend(old_piles[2])
if mid_pile == 3 :
newlist.extend(old_piles[0])
newlist.extend(old_piles[2])
newlist.extend(old_piles[1])
return newlist
If old_piles was to be :
[['S8', 'S6', 'H3', 'DK', 'D8', 'C8', 'D2'], ['SQ', ',H2', 'S2', 'S4', 'D7', 'CK', 'SJ'], ['CA', 'D3', 'DQ', 'DJ', 'C9', 'H10', 'S7']]
And mid_pile was 3, how would I get this to work??
Upvotes: 1
Views: 94
Reputation: 22776
You can just use list addition :
def remake_list(old_piles,mid_pile) :
print(old_piles)
newlist = []
if mid_pile == 1 :
newlist = old_piles[1] + old_piles[0] + old_piles[2]
if mid_pile == 2 :
newlist = old_piles[0] + old_piles[1] + old_piles[2]
if mid_pile == 3 :
newlist = old_piles[0] + old_piles[2] + old_piles[1]
return newlist
Upvotes: 1
Reputation: 9833
Use itertools.chain
import itertools
deck = [['S8', 'S6', 'H3', 'DK', 'D8', 'C8', 'D2'], ['SQ', ',H2', 'S2', 'S4', 'D7', 'CK', 'SJ'], ['CA', 'D3', 'DQ', 'DJ', 'C9', 'H10', 'S7']]
print(list(itertools.chain(*deck)))
>> ['S8', 'S6', 'H3', 'DK', 'D8', 'C8', 'D2', 'SQ', ',H2', 'S2', 'S4', 'D7', 'CK', 'SJ', 'CA', 'D3', 'DQ', 'DJ', 'C9', 'H10', 'S7']
Upvotes: 1