我正在用python 34創建一個基於文本的冒險遊戲(不是用pygame),我有一類角色。然後我把這些角色分成兩個列表:善與惡。然後我在他們之間有一系列的戰鬥,但我不知道如何從列表中刪除一個字符,如果它死了。戰鬥是隨機的,所以每次都會有不同的角色獲勝,這意味着我需要一大塊代碼才能從列表中移除角色,具體取決於誰贏得了戰鬥。如何在條件語句中從列表中刪除元素?
1
A
回答
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
您可以致電刪除()你的好名單和邪惡列表,如果你傳遞你正在刪除的角色。
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
== 這是你想要的嗎?
相關問題
- 1. 如何有條件地從元組列表中刪除元素?
- 2. 如何從列表中刪除元素
- 3. 從HTML中刪除條件語句/ xml
- 4. 刪除元素,並從列表中刪除下列元素
- 5. 從元組列表中刪除元素
- 6. 如何從字典中的列表中刪除列表元素?
- 7. kdb +:根據條件從列表中刪除元素
- 8. 從列表中刪除一些滿足條件的元素
- 9. 如何刪除列表中的元素?
- 10. 如何在特定條件下從元素中刪除Bootstrap Affix?
- 11. 如何從Python列表中刪除列表元素
- 12. python如何從列表中刪除元素的排序列表?
- 13. Lisp,如何從列表中刪除元素列表?
- 14. 從列表中刪除元素
- 15. 從列表中動態刪除元素
- 16. 從列表中增量刪除元素
- 17. 從標準列表中刪除元素
- 18. 從鏈接列表中刪除元素
- 19. 元素不從列表中刪除
- 20. 從列表中刪除偶數元素
- 21. 從C++列表中刪除元素
- 22. 從鏈接列表中刪除元素
- 23. 從python列表中刪除元素
- 24. 從鏈接列表中刪除元素
- 25. 從python3的列表中刪除元素
- 26. 從列表中刪除當前元素
- 27. 從通用列表中刪除元素
- 28. 從列表中刪除元素
- 29. 從內核列表中刪除元素
- 30. 從列表元素中刪除項目?
注意第二行代碼將只刪除字符串中的第一個'value_of_the_element_to_be_removed'。作爲Allen mentioend的 –