首页 > 解决方案 > 如何从列表中删除项目并将其分配给变量?

问题描述

对于一些背景,如果您有兴趣,我在 python 方面有一些经验,但我已经有几年没有接触过它了——我主要使用基本但我想了解更多关于 python 的知识。

我正在尝试编写一个基于卡片的游戏,其中列表(卡片组)中的项目被分发给玩家。我知道这通常是不好的做法,但是我为每个玩家创建了 5 个“卡槽”,我试图将卡从列表底部(甲板)移动到这个槽中,这将使游戏的其余部分编程要简单得多。

#import and shuffle cards
with open("deck.txt") as f:
        cards = f.readlines()

random.shuffle(cards)

#move bottom card to first slot (p1c1 stands for person 1 card 1)

p1c1 = cards(0)
cards.remove(a[0])

我收到此错误行

Traceback (most recent call last):
  File "C:/Users/harry/OneDrive/Documents/python/21.py", line 41, in <module>
    p1c1 = int(cards(0))
TypeError: 'list' object is not callable

标签: pythonlist

解决方案


easy way - does assignment and removes item all at once.

p1c1 = cards.pop(0)

& the comments are right, to index a list you need to use square brackets.


推荐阅读