2017-05-08 56 views
1

我正在用python 34創建一個基於文本的冒險遊戲(不是用pygame),我有一類角色。然後我把這些角色分成兩個列表:善與惡。然後我在他們之間有一系列的戰鬥,但我不知道如何從列表中刪除一個字符,如果它死了。戰鬥是隨機的,所以每次都會有不同的角色獲勝,這意味着我需要一大塊代碼才能從列表中移除角色,具體取決於誰贏得了戰鬥。如何在條件語句中從列表中刪除元素?

回答

0

如果你知道從你的列表中移除元素的索引,你可以這樣做:

yourlist.pop(index_of_the_element_to_be_removed) 

如果你知道元素的值將被從列表中刪除,你可以這樣做:

yourlist.pop(yourlist.index(value_of_the_element_to_be_removed)) 

如果你想刪除所有與價值的元素,你可以這樣做:

[e for e in yourlist if e!=value_of_the_element_to_be_removed] 
+0

注意第二行代碼將只刪除字符串中的第一個'value_of_the_element_to_be_removed'。作爲Allen mentioend的 –

0

您可以致電刪除()你的好名單和邪惡列表,如果你傳遞你正在刪除的角色。

good_list.remove('good_guy') 

bad_list.remove('bad_guy') 
+0

,你也可以使用list.pop() –

0

根據我的理解,我試圖模擬一個隨機-VS-一拼每一輪。

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))) 

==打印結果

好失落good2_tiger在與同evil1_elephant 戰鬥good3_bird 好失落good1_fox戰鬥與evil1_elephant 邪惡失去evil2_lion爭取保持良好的戰士:good3_bird 留守邪惡戰士:evil1_elephant ,evil3_chicken

== 這是你想要的嗎?