填充一个列表/列表列表,文件中没有重复数据

时间:2018-10-19 08:20:39

标签: python list

因此,我需要从文件中加载一些名称并创建一个当前可以使用的列表,但是名称不应重复,我可以弄清楚我尝试使用random.sample来解决问题,但由于它处于循环状态,因此变得毫无意义。

  def open_cards(number_of_cards):
    cards = []
    txtfile="mytextfile.txt"
    file = open(txtfile).read().splitlines()
    for x in range (0, int(number_of_cards) * 2):
        listy = []
        xmen_name = random.choice(file)
        power = random.randint(0, 100)
        intelligence = random.randint(0, 50)
        weakness = random.randint(0, 10)
        spirit = random.randint(0, 10)
        listy.insert(0, xmen_name)
        listy.insert(1, power)
        listy.insert(2, intelligence)
        listy.insert(3, weakness)
        listy.insert(4, spirit)
        cards.append(listy)
    print("this is the card list prior to shuffle")
    print(cards)

3 个答案:

答案 0 :(得分:0)

如果不应重复输入内容,这听起来像dict的工作。所以:

cards = {}
for x in range (0, int(number_of_cards) * 2):
    # code
    cards[xmen_name] = (power, intelligence, weakness, spirit)

我会说使用元组,我不认为应该修改XMen统计信息:)

答案 1 :(得分:0)

我会使用random.shuffle

先改组名称,然后进行迭代

(我不明白为什么您要创建number_of_cards * 2张卡,而不仅仅是number_of_cards张)

def open_cards(number_of_cards):
    cards = []
    txtfile="mytextfile.txt"
    with open(txtfile) as f:
        names = list(f)
    random.shuffle(names)
    for i in range(number_of_cards * 2):
        listy = []
        xmen_name = names[i]
        power = random.randint(0, 100)
        intelligence = random.randint(0, 50)
        weakness = random.randint(0, 10)
        spirit = random.randint(0, 10)
        listy.append(xmen_name)
        listy.append(power)
        listy.append(intelligence)
        listy.append(weakness)
        listy.append(spirit)
        cards.append(listy)
    print("this is the card list prior to shuffle")
    print(cards)

答案 2 :(得分:0)

您可以使用set删除list中的重复值

Listy = [power, intelligence, weakness, spirit, weakness, power]
unique_listy = set(Listy)
print(unique_listy)

输出

{power, intelligence, weakness, spirit}