如何随机找到元素时从2D数组中删除元素

时间:2015-10-11 20:05:23

标签: python multidimensional-array

spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']

hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']

clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']

diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']

suits = [spades,hearts,clubs,diamonds]

import random

card1 = suits[int(random.random()*4)][int(random.random()*13)]

card2 = suits[int(random.random()*4)][int(random.random()*13)]

card3 = suits[int(random.random()*4)][int(random.random()*13)]

print(card1,card2,card3)

for i in suits:

    if card1 == i:

        suit.remove(i)
print(suits)

3 个答案:

答案 0 :(得分:0)

试试这个:

for suit in suits:
    if card1 in suit:
        suit.remove(card1)

答案 1 :(得分:0)

你可以先保存你的随机位置,然后拿到你的牌(因为它的随机位置会随机选择),最后你可以删除它们,因为你有他们的位置。

spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']

hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']

clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']

diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']

suits = [spades,hearts,clubs,diamonds]

import random

suit_pos_1, card_pos_1 = int(random.random()*4), int(random.random()*13)
suit_pos_2, card_pos_2 = int(random.random()*4), int(random.random()*13)
suit_pos_3, card_pos_3 = int(random.random()*4), int(random.random()*13)

card1 = suits[suit_pos_1].pop(card_pos_1)
card2 = suits[suit_pos_2].pop(card_pos_2)
card3 = suits[suit_pos_3].pop(card_pos_3)

print(card1,card2,card3)

suit[suit_pos_1].pop(card_pos_1)
suit[suit_pos_2].pop(card_pos_2)
suit[suit_pos_3].pop(card_pos_3)

print(suits)

但是在执行之后,你的套装阵列将没有13张牌。 所以我建议做类似的事情:

suit_pos_1 = int(random.random()*len(suits))
card_pos_1 = int(random.random()*len(suits[suit_pos_1]))

祝你好运, 贡萨洛。

答案 2 :(得分:0)

你必须循环两次,穿上西装,然后穿上西装的每个清单

spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']

hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']

clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']

diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']

suits = [spades,hearts,clubs,diamonds]


print("cards before removing {} ".format(sum(map(len,suits))))

import random

card1 = suits[int(random.random()*4)][int(random.random()*13)]

card2 = suits[int(random.random()*4)][int(random.random()*13)]

card3 = suits[int(random.random()*4)][int(random.random()*13)]

print(card1,card2,card3)

for i in suits:

    for card in i:
        if card1 == card:
            print("removed {}".format(card1))
            i.remove(card1)
            break


 print("cards after removing {} ".format(sum(map(len,suits))))

cards before  removing 52 
9H QD 5C
removed 9H
cards after removing 51