简体   繁体   English

如何从列表中删除项目,并将其分配给变量?

[英]How can I remove an item from a list, and assign it to a variable?

For some background if you're interested, I have a bit of experience in python but I haven't touched it in a couple of years - I mainly used basic but im looking to learn more of python. 对于某些背景,如果您感兴趣的话,我对python有一定的经验,但是几年没接触过-我主要使用基本语言,但是我想学习更多关于python的知识。

I am trying to program a card based game, where items from a list (the deck of cards) are dealt out to players. 我正在尝试对基于纸牌的游戏进行编程,将列表(纸牌)中的项目分配给玩家。 I understand that this is usually bad practice, but I have created 5 "card slots" for each player which I am trying to move the card from the bottom of the list (deck) into this slot, this would make the rest of the game much simpler to program. 我知道这通常是不好的做法,但是我为每个球员创建了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])

I am being given this error line 我收到此错误行

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

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. &注释正确,要索引列表,您需要使用方括号。

The pop function (see here ) takes an index, and removes it while returning that item. pop函数(请参阅此处 )获取索引,并在返回该项目时将其删除。

p1c1 = cards.pop(0)

Also note that to access a certain item in a list you use square brackets - so here's your now-working approach: 另请注意,要访问列表中的特定项目,请使用方括号-这是您现在可以使用的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM