使用zip函数时,使用列表推导创建具有单个元素的列表

时间:2019-01-09 19:11:47

标签: python list zip list-comprehension

我一直在尝试以特定方式对列表进行洗牌:

def shuffle(card_deck):
shuffled = list()
deck_size = len(card_deck) // 2

lhand_deck = card_deck[0: deck_size]
rhand_deck = card_deck[deck_size: deck_size*2]

for i, j in zip(lhand_deck, rhand_deck):
    shuffled.append(i); shuffled.append(j)

return shuffled

为了提高更大牌组的表现,我决定使用列表理解:

shuffled = [
    i
    for i in zip(lhand_deck, rhand_deck)
]

现在列表包含元组,但是我希望它包含单个元素:

shuffled = [0, 2, 1, 3]

代替

shuffled = [(0,2), (1, 3)]

*在这种情况下不起作用,因为它会引发错误。是否有任何方法或只能使用循环?感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您可以使用嵌套列表推导来展平输出:

shuffled = [
    i
    for t in zip(lhand_deck, rhand_deck)
    for i in t
]

答案 1 :(得分:1)

您可以使用itertools.chain来展平元组列表:

shuffled = list(chain.from_iterable(zip(lhand_deck, rhand_deck)))

以下示例列表将提供:

shuffle([1,3,5,2,1])
[1, 5, 3, 2]