找到一个特定python变量的名称并用python打印出来

2024-10-03 09:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

现在它已经返回了列表1中最小项的值,我希望它在下一行显示这个值的名称。有人能告诉我如何让python打印列表中最小值的名称并显示它的值吗。你知道吗

bpPetrol = 099.9
bpDiesel = 100.9

shellPetrol = 102.9
shellDiesel = 103.9

texacoPetrol = 100.9
texacoDiesel = 101.9

gulfPetrol = 098.9
gulfDiesel = 102.9

tescoPetrol = 100.9
tescoDiesel = 102.9

list1= [bpPetrol, shellPetrol, texacoPetrol, gulfPetrol, tescoPetrol]
list2= [bpDiesel, shellDiesel, texacoDiesel, gulfDiesel, tescoDiesel]

if searchRadius < 10:
    if fuelType == "Petrol":
        print("The cheapest price of petrol today is:"), min(list1)
        print("")
        print ("This can be found at the")position in list1("petrol         station")
        print("The average price of petrol at all the stations today     is:"),avgPetrol 
        print("Just in case you were intersted, the average price of d     diesel today is:"),avgDiesel

Tags: ofthe名称列表todayispriceprint
3条回答

print()函数中包含变量,例如:

value = 12
print('My value:', value)

您的值在print()函数之外,比如print('My value:'), value。你知道吗

bpPetrol = 099.9
bpDiesel = 100.9

shellPetrol = 102.9
shellDiesel = 103.9

texacoPetrol = 100.9
texacoDiesel = 101.9

gulfPetrol = 098.9
gulfDiesel = 102.9

tescoPetrol = 100.9
tescoDiesel = 102.9

namelist=['bp', 'shell', 'texaco', 'gulf', 'tesco']
list1= [bpPetrol, shellPetrol, texacoPetrol, gulfPetrol, tescoPetrol]
list2= [bpDiesel, shellDiesel, texacoDiesel, gulfDiesel, tescoDiesel]

fuelType="Petrol"

if fuelType == "Petrol":
    minPetrolPrice=min(list1)
    minPetrolPriceIndex=list1.index(min(list1))
    minPetrolPriceName=namelist[minPetrolPriceIndex]
    print("The cheapest price of petrol today is: ", minPetrolPrice)
    print("")

    print("This can be found at the position ", minPetrolPriceIndex, "in list1 and petrol station name is ", minPetrolPriceName)
    print("The average price of petrol at all the stations today is:", (sum(list1)/float(len(list1))))
    print("Just in case you were intersted, the average price of d diesel today is:", (sum(list2)/float(len(list2))))

上面的程序显示了最低汽油价格、加油站名称和指数以及平均值

更好的方法是使用名称与价格对应的词典

如果要显示最便宜品牌的名称,可以单独存储名称,甚至检查globals()locals()输出,但如果在列表中存储词典(或对象,或一些结构化数据),则会容易得多。你知道吗

例如:

petrol_prices = [{
  'brand': 'BP',
  'price': 099.9,
},{
  'brand': 'Shell',
  'price': 102.9,
},
# etc...
]

然后您可以使用the ^{} argument of the ^{} function处理这些列表:

smallest = min(petrol_prices, key=lambda x: x['price'])
print("Cheapest brand: ", smallest['brand'], ", price: ", smallest['price'])

如果您需要关于lambda函数的更多信息,可以检查this question。如果愿意,还可以给key参数一个正则函数。你知道吗

相关问题 更多 >