如何使用变量来确定要使用列表中的哪个索引
Posted
技术标签:
【中文标题】如何使用变量来确定要使用列表中的哪个索引【英文标题】:How to use a variable to determine which index in a list to use 【发布时间】:2020-08-24 14:15:53 【问题描述】:我最近一直在测试我的一个程序,每次我测试它时,我都会收到相同的错误消息: IndexError:列表索引超出范围 代码是
def NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers):
x = random.randint(0, NoOfBuyers)
SelectedBuyer = Buyers[x]
if CurrentOffer < MaximumPrice[x]:
CurrentOffer = CurrentOffer + random.randint(1, 500)
print(str(SelectedBuyer) + " renewed their offer and are now willing to pay £" +
str(CurrentOffer) + " for " + str(AuctionedItem))
x = random.randint(0, NoOfBuyers)
NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers)
time.sleep(3)
唯一每次都会出错的行是 ''' SelectedBuyer = Buyers[x] '''。我该如何解决这个问题?
【问题讨论】:
【参考方案1】:买家列表中的位置 x 似乎没有元素,您可以通过以下方式检查它
Buyers[x] if len(Buyers) >= x else #some value if it's not in the len()
或
x = random.randint(0, len(Buyers) - 1)
生成一个与买家列表长度一致的随机数。
您可能需要对MaximumPrice
执行相同操作
【讨论】:
【参考方案2】:我试图理解你的代码并想出了另一个实现:
import random
import time
buyers = (
("Peggy Carter", 10000),
("Phil Coulson", 7500),
("Edwin Jarvis", 5000),
("Justin Hammer", 2300),
("Darcy Lewis", 1750),
("Christine Everhart", 6490),
)
auctioned_item = "The Tesseract"
current_offer = random.randint(1, 5000)
print(f"The starting price for auctioned_item is £current_offer")
current_buyer = None
def auction_rounds(current_offer, buyers):
current_buyer = None
outbid = False
while not outbid:
(next_buyer, next_maximum) = random.choice(buyers)
while next_buyer == current_buyer:
(next_buyer, next_maximum) = random.choice(buyers)
outbid = current_offer > next_maximum
if not outbid:
current_buyer = next_buyer
yield (current_buyer, current_offer)
next_offer = random.randint(current_offer, min(current_offer + 500,
next_maximum))
current_buyer, current_offer = next_buyer, next_offer
else:
print(f'This is too much for next_buyer')
for (current_buyer, current_offer) in auction_rounds(current_offer, buyers):
print(f"current_buyer is offering to pay £current_offer",
"for", auctioned_item)
#time.sleep(3)
if current_buyer is None:
print("The first buyer wasn't even able to pay the starting price")
else:
print(f"Sold! The auction item (auctioned_item) is awarded to current_buyer for £current_offer")
我希望这就是你正在寻找的那种东西。
【讨论】:
以上是关于如何使用变量来确定要使用列表中的哪个索引的主要内容,如果未能解决你的问题,请参考以下文章