从循环列表中删除元素

时间:2020-04-04 10:51:43

标签: python list loops error-handling element

import stdio
import sys
import random

SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"]
RANKS = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen ", "King", "Ace"]


rank = random . randrange (0 , len( RANKS ))
suit = random . randrange (0 , len( SUITS ))
stdio . writeln ( RANKS [ rank ] + "of" + SUITS [ suit ])

deck = []
for rank in RANKS :
    for suit in SUITS :
        card = rank + "of" + suit
        deck += [ card ]


n = len ( deck )
for i in range ( n ):
    r = random . randrange (i , n)
    temp = deck [r]
    deck [r] = deck [i]
    deck [i] = temp


h = []

b = int(sys.argv[1])

k = 1
for l in range(b):
    while k <= b:
        f = random.randrange(n)
        h += [deck[f]]
        deck.pop([deck[f]]) # this line is the problem, i wnat to move [deck[f]], from deck but getting a                      
                               type eror
        k += 1
    print(h)

#这是我的命令提示符

文件“ C:\ Users \ USER \ Desktop \ app \ pokerhands.py”,第37行,在 deck.pop([deck [f]]) TypeError:“列表”对象无法解释为整数

3 个答案:

答案 0 :(得分:1)

尝试使用deck.pop([deck[f]])代替deck.pop(f)

list.pop(index)删除index处的元素。您正在尝试使用包含字符串而不是整数的列表作为索引。

答案 1 :(得分:0)

使用del deck[f]或使用deck.pop["index of element in deck"]

答案 2 :(得分:0)

欢迎堆栈溢出。

我注意到您正在做两件事。

首先

.pop(arg)是一个内置的python函数,它以 index 作为参数而不是数组值。

因此,假设您要从循环内的列表中随机删除元素,请首先将deck.pop([deck[f]])更改为deck.pop(f)

第二

您正在从(0,n)之间随机选择一个索引从列表中删除。但是,在每次迭代中,您都没有减小n的值,因此可能会使索引数组超出范围异常。简单的解决方法是仅在每次迭代中减小n的值。像这样:

n -= 1