簡體   English   中英

選擇后從列表中刪除

[英]Remove from list as choices are made

我正在嘗試創建一個通過隨機分配種族,職業和統計信息來創建角色的程序。

但是我希望每個統計信息都有一個唯一的值。 因此,如果strength是8,那么其他任何統計都不能是8。我該怎么做呢? 選擇后是否需要刪除列表條目?

我的密碼

import random

races = ["Human", "Dwarf", "Elf"]
classes = ["Fighter", "Wizard", "Rogue"]
stats = [8, 10, 11, 12, 14, 15]

Strength = 0
Dexterity = 0
Constution = 0
Intelligence = 0
Wisdom = 0
Charisma = 0

Strength = random.choice(stats)
Dexterity = random.choice(stats)
Constution = random.choice(stats) 
Intelligence = random.choice(stats)
Wisdom = random.choice(stats)
Charisma = random.choice(stats)

race = random.choice(races)
clse = random.choice(classes)

創建stats列表的隨機排列,然后按排列順序分配“ Strength ,“ Dexterity等。 這具有額外的好處,即您無需在創建新角色之前重置列表。

from random import shuffle

# ...
stats = [8, 10, 11, 12, 14, 15]
shuffle(stats)
Strength = stats[0]
Dexterity = stats[1]
Constution = stats[2]
Intelligence = stats[3]
Wisdom = stats[4]
Charisma = stats[5]

附帶說明一下,不需要將默認值0分配給Strength等,因為它們將在之后立即更改。

就像您在問題中說的那樣,您可以從列表中刪除條目:

Strenght = random.choice(stats)
del stats[stats.index(Strength)]

就像我在上面的答案中所說的那樣,一個好的解決方案也是使用random shuffle 加上一個提示,例如在編寫Strength = random.choice(stats)您會在那一刻聲明變量Strength並為其提供一個值,這樣就不必在其上方聲明它,因此可以刪除所有這些Strength = 0和等等

您顯示給我們的內容只需要1個字符。 但是,如果我們要創建數百個呢? 在Python中,所有內容都是一個類,在這種情況下,強烈建議使用它。

看這個簡單的例子:

import random
from textwrap import dedent

races = ["Human", "Dwarf", "Elf"]
classes = ["Fighter", "Wizard", "Rogue"]
stats = [ 8, 10, 11, 12, 14, 15]

class char:
    def __init__(self, races, classes, stats):
        random.shuffle(stats) # <--- this solves your problem
        self.race = random.choice(races)
        self.cls = random.choice(classes)
        self.stats = dict(zip(['Strength','Dexterity','Constution',
                               'Intelligence','Wisdom','Charisma'],stats))

    def __str__(self):
        s = dedent('''\
        Your character is a....
        Race: {}
        Class: {}
        Stats: {}''').format(self.race, self.cls, self.stats)
        return s

char1 = char(races,classes,stats) # Creates char1 based on char class
char2 = char(races,classes,stats) # Creates char2 ...

print(char1) # printing a class will call the __str__ function if it exists
print()
print(char2)

一個類可以容納變量和其他函數,在這種情況下,我們創建三個變量(race,cls和stats),並添加一個打印函數以輕松打印所擁有的內容。

當我運行它時返回:

Your character is a....
Race: Elf
Class: Rogue
Stats: {'Dexterity': 11, 'Charisma': 15, 'Constution': 12, 'Wisdom': 10, 'Intelligence': 14, 'Strength': 8}

Your character is a....
Race: Dwarf
Class: Fighter
Stats: {'Dexterity': 14, 'Charisma': 8, 'Constution': 12, 'Wisdom': 11, 'Intelligence': 15, 'Strength': 10}

您可以將random.choice的值存儲在臨時文件中。 變量和用途

stats.remove(temp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM