如何在条件语句中从列表中删除元素?

时间:2017-05-08 01:35:29

标签: python

我正在使用python 34(不是pygame)创建一个基于文本的冒险游戏,我有一类角色。然后我把这些角色分成两个列表:好的和邪恶的。然后我们之间有一系列的争斗,但我不知道如果它死了,如何从列表中删除一个字符。战斗是随机的,所以每次都会赢得一个不同的角色,这意味着我需要一大堆代码才能从列表中删除一个角色,具体取决于谁赢得了战斗。

1 个答案:

答案 0 :(得分:0)

根据我的理解,我尝试模拟每轮一对一的随机战斗。

import random
from __future__ import print_function
characters = ['good1_fox','evil1_elephant','good2_tiger','evil2_lion','good3_bird','evil3_chicken']
# Try to split characters into two lists
good = [x for x in characters if 'good' in x]
evil = [x for x in characters if 'evil' in x]
# Total round of fight
n = 3
for i in xrange(n):
    good_fighter = random.choice(good)
    evil_fighter = random.choice(evil)
    # set the condition of winning
    if len(good_fighter) >= len(evil_fighter):
        # Remove fighter from the list
        evil.remove(evil_fighter)
        print("evil lost {} in fighting with {}".format(evil_fighter, good_fighter))    
    else:
        # Remove fighter from the list          
        good.remove(good_fighter)
        print("good lost {} in fighting with {}".format(good_fighter, evil_fighter))    
print("Remained good fighters: {}\nRemained evil fighters: {}\n".format(", ".join(good),", ".join(evil)))

==打印结果

在与evil1_elephant的战斗中失去了良好的感情 邪恶在与good3_bird的战斗中失去了evil2_lion 善于在与evil1_elephant的战斗中失去了good1_fox 剩下的好战士:good3_bird 剩下的邪恶战士:evil1_elephant,evil3_chicken

== 这是你想要的吗?