[英]I am trying to print out the highest bidder in my list of dictionaries
I am trying to loop through my list of dictionaries and print out the highest bidder in my list of dictionaries.我正在尝试遍历我的字典列表并打印出我的字典列表中出价最高的人。 In a for loop with python is 'i' not automatically an integer?在带有 python 的 for 循环中,“我”不会自动成为 integer?
Example: for i in dictionary: Does i not equal 0, 1, 2 so on?示例:对于字典中的 i:i 不等于 0、1、2 等等吗?
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
for i in bidders:
bid = bidders[i]["bid"]
name = bidders[i]["name"]
if bid > bid:
print(f"Congratulations {name}! Your bid of ${bid} wins!")
else:
print(f"Congratulations {name}! Your bid of ${bid} wins!")
No, since you are not calling the range function i is not default a integer.不,因为您没有调用范围 function,所以我不是默认的 integer。 Leonardo's answer looks more correct, however what I wrote down below would also work.莱昂纳多的答案看起来更正确,但是我在下面写下的内容也可以。
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
maxBid = -1
maxBidName = "";
for i in range(0, len(bidders)):
bid = bidders[i]["bid"]
name = bidders[i]["name"]
if bid > maxBid:
maxBid = bid
maxBidName = name
print(f"Congratulations {maxBidName}! Your bid of ${maxBid} wins!")
I believe what you're looking for is bid = i['bid']
.我相信您正在寻找的是bid = i['bid']
。 i
in this case is simply part of the dictionary.在这种情况下, i
只是字典的一部分。 So for each entry, you want the value of 'bid'
.因此,对于每个条目,您都需要'bid'
的值。
there are few mistakes, i think this will works几乎没有错误,我认为这会起作用
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
highestBid = 0
highestBidData = {}
for i in bidders:
if i['bid'] > highestBid:
highestBid = i['bid']
highestBidData = i
print("Congratulations {0}! Your bid of {1} `enter code
here`wins!".format(highestBidData['name'],highestBidData['bid']))
bidders = [
{
"name": "nicholas",
"bid": 12,
},
{
"name": "jack",
"bid": 69,
},
]
maxBidder = max(bidders, key=lambda x:x['bid'])
print("Congratulations {}! Your bid of {} wins!".format(maxBidder['name'],maxBidder['bid']))
In a for loop with python is 'i' not automatically an integer?在带有 python 的 for 循环中,“我”不会自动成为 integer?
Example: for i in dictionary: Does i not equal 0, 1, 2 so on?示例:对于字典中的 i:i 不等于 0、1、2 等等吗?
No不
A very easy way to find out what it is is simply:一个非常简单的方法来找出它是什么:
for i in bidders:
print(i)
print(type(i))
Output: Output:
{'name': 'nicholas', 'bid': 12}
<class 'dict'>
{'name': 'jack', 'bid': 69}
<class 'dict'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.