[英]Removing an element from a list in the loop
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]]) 中类型错误:'list' object 不能解释为 integer
代替deck.pop([deck[f]])
,试试deck.pop(f)
。
list.pop(index)
删除index
处的元素。 您正在尝试使用包含字符串作为索引的列表,而不是 integer。
使用del deck[f]
或使用deck.pop["index of element in deck"]
。
欢迎来到堆栈溢出。
我注意到你正在做两件事。
.pop(arg)
是一个内置的 python function ,它将索引作为参数,而不是数组值。
因此,首先将deck.pop([deck[f]])
更改为deck.pop(f)
,假设您想从循环内的列表中随机删除元素。
您正在随机选择 (0, n) 之间的索引以从列表中删除。 但是,在每次迭代中,您都不会减少n
的值,因此,可能会导致索引数组越界异常。 简单的解决方法是在每次迭代中减少n
的值。 像这样:
n -= 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.