[英]Python, how to randomly add/append elements from one list to another?
[英]How to append items from one list to another in Python 3
我正在尝试为GCSE Computer Science编写“ Card Trick”练习程序,但是我只能使用一种功能。
我有一个包含3个其他数组的数组,我想将3个数组中的项目取走并将它们移到另一个列表中。
这是我拥有的代码,我不确定为什么它不起作用:
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
如果old_piles是:
[['S8', 'S6', 'H3', 'DK', 'D8', 'C8', 'D2'], ['SQ', ',H2', 'S2', 'S4', 'D7', 'CK', 'SJ'], ['CA', 'D3', 'DQ', 'DJ', 'C9', 'H10', 'S7']]
mid_pile是3,我将如何使用它?
使用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']
您可以只使用列表添加:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.