【问题标题】:Removing an element from a list in the loop从循环中的列表中删除元素
【发布时间】:2020-04-04 10:51:43
【问题描述】:
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 行,在 甲板.pop([甲板[f]]) TypeError: 'list' 对象不能被解释为整数

【问题讨论】:

  • 您需要指定要删除的项目的索引而不是值。试试:`deck.pop(f)'

标签: python list loops error-handling element


【解决方案1】:

试试deck.pop(f),而不是deck.pop([deck[f]])

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      欢迎来到堆栈溢出。

      我注意到你在做两件事。

      首先

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

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

      其次

      您正在随机选择 (0, n) 之间的索引以从列表中删除。但是,在每次迭代中,您都不会减少 n 的值,因此可能会导致索引数组越界异常。简单的解决方法是在每次迭代中减少 n 的值。像这样:

      n -= 1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-08
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-03
        • 2021-06-21
        相关资源
        最近更新 更多