从左到右逐行排序3堆数字

时间:2017-05-18 17:36:14

标签: python list sorting

嘿我需要在它们混合后以特殊的方式排序3个列表,然后逐行排列(Link to the full question):

a=[1,2,3]
b=[4,5,6]
c=[7,8,9]

现在订单是b,a,c,你必须从左到右放置所有数字(我需要为一个套牌执行此操作,因此数字将包含它们旁边的字母,使它们成为一个字符串)。 / p>

预期结果:

  • a = [4,1,7]
  • b = [5,2,8]
  • c = [6,3,9]

*请注意我正在处理的列表中包含3个以上的值

3 个答案:

答案 0 :(得分:2)

只需zip他们:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=[7,8,9]

>>> a, b, c = map(list, zip(b, a, c))  # in the order specified: b, a, c

>>> a
[4, 1, 7]
>>> b
[5, 2, 8]
>>> c
[6, 3, 9]

它也可以使用(但可以就地更改列表):

>>> a[:], b[:], c[:] = zip(b, a, c)

而不是map(list, ...)

如果您有更多值并希望分发它们:

>>> a=[1,2,3,4]
>>> b=[5,6,7,8]
>>> c=[9,10,11,12]

>>> tmp = b + a + c   # concatenate them in the order

>>> # distribute them: every third element, starting with 0 (a), 1 (b) and 2 (c)
>>> a, b, c = tmp[::3], tmp[1::3], tmp[2::3]  

>>> a
[5, 8, 3, 10]
>>> b 
[6, 1, 4, 11]
>>> c
[7, 2, 9, 12]

答案 1 :(得分:0)

选择所选桩后,需要将选定的桩放在另外两桩的中间。一种选择就是将三个不同的桩列表合并到一个列表中,选择的桩位于中间。

if pile == 1: NewCards = Pile2 + Pile1 + Pile3
elif pile == 2: NewCards = Pile1 + Pile2 + Pile3
else: NewCards = Pile1 + Pile3 + Pile2

编辑: 好的,所以你需要把卡的组合分成3堆。你可以遍历每个甲板,然后处理它们。确保右侧甲板位于中间! (在这种情况下,我将使用甲板2)。

 # create three empty temporary lists
 temp = [[],[],[]]
 cardnum = 0

 # loop through the 3 decks
 for i in range(3):
     if i == 0: deck = partA
     elif i == 1: deck = partB
     else: deck = partC

     # loop through the cards in the decks
     for card in deck:
         i = cardnum % 3 # mod 3 to split the cards among the decks
         temp[i] += card
         cardnum += 1

# update the decks now
partA = temp[0]
partB = temp[1]
partC = temp[2]

答案 2 :(得分:0)

嗯......一个有趣的问题:P

当人们对我做的时候,我会做一些我讨厌的事情...邮政编码...... 看看这里有什么东西可以帮助你。

提示:看一下get_order函数。

from itertools import product, izip_longest
import random

def grouped(iterable, n, fillvalue=None):
    return izip_longest(fillvalue=fillvalue, *[iter(iterable)] * n)

def get_order(selected, seq=[0,1,2]):
    seq = [i for i in seq if i!=selected]
    seq.insert(len(seq)/2, selected)
    return seq


deck = ['-'.join(card) for card in product('c h d s'.split(), 'a 1 2 3 4 5 6 7 8 9 10 j q k'.split())]
plycards= random.sample(deck,21)

piles = [[],[],[]]
for idx, i in enumerate(grouped(plycards, 3)):
    for idx, item in enumerate(i):
        piles[idx].append(item)
    print (i)

for j in range(0,3):
    # Combine again 
    plycards = []
    for i in get_order(int(raw_input('Which pile? '))-1):
        plycards += piles[i]
    print ('-------------')
    piles = [[],[],[]]
    for idx, i in enumerate(grouped(plycards, 3)):
        for jdx, item in enumerate(i):
            piles[jdx].append(item)
        print (i)

print ("You selected card :'{}'".format(plycards[10])