如何将我删除的列表中的项目添加到另一个列表中?

Posted

技术标签:

【中文标题】如何将我删除的列表中的项目添加到另一个列表中?【英文标题】:How can I add the items form list that I removed to another list? 【发布时间】:2021-02-23 00:58:43 【问题描述】:

如何将我删除的卡片添加到我的手单中?抽牌会移除卡片,但我不知道如何将这些移除的卡片添加到手牌列表中。

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
"sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
"dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
"cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
"h10", "hJ", "hQ", "hK"]

def draw():
  if len(deck) == 52:
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
    random_item_from_deck = random.choice(deck)
    deck.remove(random_item_from_deck)
 

hand=[]
hand.append()


print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))

【问题讨论】:

【参考方案1】:

对于“转移这些卡”的概念,您会遇到很多麻烦。洗牌并从顶部取出 5 张牌:

random.shuffle(deck)
player_hand, remaining_deck = deck[:5], deck[5:]

这会处理你的案子吗?

【讨论】:

【参考方案2】:

您可以启动一个空列表并使用其.append() 方法

>>> l = ['a', 'b', 'c']
>>> l.append('d')
>>> l
['a', 'b', 'c', 'd']

对于这种情况,您可能还会发现set 在您只有其中一个时很实用,因为它具有方便的成员资格方法

>>> s = set(('a', 'b', 'c'))
>>> s.remove('a')
>>> s
'c', 'b'
>>> s - set(('a', 'c'))
'b'

但是,正如 @Prune 所说,shuffling and then slicing the deck 可能更干净!

【讨论】:

【参考方案3】:

由于牌组中的所有牌都是唯一的,因此您可以使用它的索引先将其转移到手上,然后再将其移除。

代码:

import random

deck = ["sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ",
    "sK", "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ",
    "dQ", "dK", "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10",
    "cJ", "cQ", "cK", "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9",
    "h10", "hJ", "hQ", "hK"]

hand = [] # define hand here

def draw():
  if len(deck) == 52:
    for i in range(4): # using a for loop to avoid repetition of statements
      random_item_from_deck = random.choice(deck)
      hand.append(deck[deck.index(random_item_from_deck)])
      deck.remove(random_item_from_deck)
        
print ("cards in deck : " + str(deck))
draw()
print ("Deck after removal of cards : " + str(deck))
print ("Cards in hand : " + str(hand))

【讨论】:

以上是关于如何将我删除的列表中的项目添加到另一个列表中?的主要内容,如果未能解决你的问题,请参考以下文章

如何从列表中的项目中删除标点符号并将其另存为列表中的单独项目?

将项目添加到另一个活动中的列表视图(仅添加 1 个条目)

如何使用 Vue draggable 将组件列表中的项目拖动到另一个组件中的列表?

Python如何将列表中的元素添加到另一个字符串列表中

Python 中如何删除一个列表 List 中多个符合条件的元素

java swing 中的列表框JList如何在程序中动态的添加和删除元素