如何通过与 Python 3 中的另一个列表进行比较,仅从列表中弹出重复项一次
How to pop duplications only once from a list by comparing to another list in Python 3
我正在尝试编写一个纸牌游戏,为纸牌分配数值。
a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
b = [1, 2]
如何从 a
中移除 b
(你从一副牌中抽取的牌)以获得:
c = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]
或者...我如何从 a
中抽取随机样本来制作单独的列表 b
?
您可以使用 .remove()
.
remove()
- Remove first occurrence of value. Raises ValueError
if the value is not present.
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
a.remove(b[0])
a.remove(b[1])
print(a)
或者:
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
for i in b:
a.remove(i)
print(a)
如果你想要一个单独的列表,你可以创建一个列表的副本a
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
c=a.copy()
for i in b:
c.remove(i)
print(c)
random.sample(a, n)
会给你一个样本,其中 n
是你想要的样本大小:
>>> a = [1,1,1,1,2,2,2,2,3,3,3,3]
>>> random.sample(a, 5)
[2, 1, 3, 2, 2]
或者你可以random.shuffle(a)
并从头开始抽n
张牌:
>>> random.shuffle(a)
>>> a
[2, 1, 2, 2, 1, 1, 1, 3, 2, 3, 3, 3]
>>> a[:5]
[2, 1, 2, 2, 1]
import random
Deck_lst = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
Deck_lst_sequence = [i for i, v in enumerate(Deck_lst)]
Draw_cards_index = random.sample(Deck_lst_sequence, 2)
Draw_cards_value = []
for Draw_card in Draw_cards_index:
Draw_cards_value.append(Deck_lst[Draw_card])
Deck_lst.remove(Deck_lst[Draw_card])
print(Deck_lst)
print(Draw_cards_value)
我正在尝试编写一个纸牌游戏,为纸牌分配数值。
a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
b = [1, 2]
如何从 a
中移除 b
(你从一副牌中抽取的牌)以获得:
c = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]
或者...我如何从 a
中抽取随机样本来制作单独的列表 b
?
您可以使用 .remove()
.
remove()
- Remove first occurrence of value. RaisesValueError
if the value is not present.
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
a.remove(b[0])
a.remove(b[1])
print(a)
或者:
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
for i in b:
a.remove(i)
print(a)
如果你想要一个单独的列表,你可以创建一个列表的副本a
a = [1,1,1,1,2,2,2,2,3,3,3,3]
b = [1,2]
c=a.copy()
for i in b:
c.remove(i)
print(c)
random.sample(a, n)
会给你一个样本,其中 n
是你想要的样本大小:
>>> a = [1,1,1,1,2,2,2,2,3,3,3,3]
>>> random.sample(a, 5)
[2, 1, 3, 2, 2]
或者你可以random.shuffle(a)
并从头开始抽n
张牌:
>>> random.shuffle(a)
>>> a
[2, 1, 2, 2, 1, 1, 1, 3, 2, 3, 3, 3]
>>> a[:5]
[2, 1, 2, 2, 1]
import random
Deck_lst = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
Deck_lst_sequence = [i for i, v in enumerate(Deck_lst)]
Draw_cards_index = random.sample(Deck_lst_sequence, 2)
Draw_cards_value = []
for Draw_card in Draw_cards_index:
Draw_cards_value.append(Deck_lst[Draw_card])
Deck_lst.remove(Deck_lst[Draw_card])
print(Deck_lst)
print(Draw_cards_value)