Python 将列表随机分成两半

Python 将列表随机分成两半,python,list,Python,List,为了用python制作一个纸牌游戏,我制作了一个名为“cardlist”的列表,其中包含52个列表作为“卡片”。我现在要做的是为用户和计算机制作两个新的列表,以便在游戏中使用,并且它们必须包含随机的一半牌。我不知道该怎么做 import random class Lamb(): def __init__(self, weight, milk, wool, offs, thigh, fert, meat, fat): self.weight = weight

为了用python制作一个纸牌游戏,我制作了一个名为“cardlist”的列表,其中包含52个列表作为“卡片”。我现在要做的是为用户和计算机制作两个新的列表,以便在游戏中使用,并且它们必须包含随机的一半牌。我不知道该怎么做

import random
class Lamb():
    def __init__(self, weight, milk, wool, offs, thigh, fert, meat, fat):
        self.weight = weight
        self.milk = milk
        self.wool = wool
        self.offs = offs
        self.thigh = thigh
        self.fert = fert
        self.meat = meat
        self.fat = fat

   def __repr__(self):
       return f"{self.weight,self.milk,self.wool,self.offs,self.thigh,self.fert,self.meat,self.fat}"

def Read(txtfile):
datalist=[]
f = open(txtfile, "r", encoding="utf-8")
for line in f:
    datalist.append(line.split(','))
f.close()
cardlist = []
for i in datalist:
    cardlist.append(Lamb(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]))
return cardlist

如果您不关心维护
卡片列表的原始排序,您可以简单地将其洗牌,然后将前半部分给用户,将后半部分给计算机:

random.shuffle(cardlist)
split = len(cardlist) // 2
user_deck = cardlist[:split]
computer_deck = cardlist[split:]

您可以
random.shuffle
并从中间拆分。另外,如果每一行都只有您想要的信息,那么编写:
对于f:cardlist.append(Lamb(*line.split())