不确定如何在元组列表中引用元组中的元素

2024-05-08 00:29:37 发布

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

我正在尝试完成一个初学者赋值,它需要引用列表中元组中的元素,该列表使用for循环和条件输出两种类型的字符串之一,具体取决于元组中的值

Using a for loop and an if statement, go through vacc_counties and print out a message for those counties that have a higher than 30% vaccination rate.

Add another loop that prints out a message for every county, but prints different messages if the rate is above or below 30.

Example:
Benton County is doing ok, with a rate of 41.4%
Fulton County is doing less ok, with a rate of 22.1%

下面是元组列表,后面是我自己的代码:

vacc_counties = [('Pulaski', 42.7), ('Benton', 41.4), ('Fulton', 22.1), ('Miller', 9.6),
                 ('Mississippi', 29.4), ('Scotty County', 28.1)]

for tuple in vacc_counties:
    for element in tuple:
        if [1] < 30:
            print(f"{vacc_counties[0]}is doing ok, with a rate of" [1]"%")
        else [1] n > 30:
            print(f"{vacc_counties[0]}is doing ok, with a rate of" [1]"%")


Tags: ofloop列表forifrateiswith
2条回答

备注:

  • 不要对变量名使用保留字,例如使用tpl而不是tuple
  • 删除for element in tuple:循环
  • 要访问元组的第二个元素,请使用tpl[1]而不是[1]
  • elif代替else

更正代码:

vacc_counties = [
    ("Pulaski", 42.7),
    ("Benton", 41.4),
    ("Fulton", 22.1),
    ("Miller", 9.6),
    ("Mississippi", 29.4),
    ("Scotty County", 28.1),
]

for tpl in vacc_counties:
    if tpl[1] < 30:
        print(f"{tpl[0]} is doing less ok, with a rate of {tpl[1]}%")
    elif tpl[1] >= 30:
        print(f"{tpl[0]} is doing ok, with a rate of {tpl[1]}%")

印刷品:

Pulaski is doing ok, with a rate of 42.7%
Benton is doing ok, with a rate of 41.4%
Fulton is doing less ok, with a rate of 22.1%
Miller is doing less ok, with a rate of 9.6%
Mississippi is doing less ok, with a rate of 29.4%
Scotty County is doing less ok, with a rate of 28.1%

您可以让Python将每个元组中的两个值解压为易于使用的变量,如下所示:

vacc_counties = [('Pulaski', 42.7), ('Benton', 41.4), ('Fulton', 22.1), ('Miller', 9.6),
                 ('Mississippi', 29.4), ('Scotty County', 28.1)]

for county, rate in vacc_counties:
    if int(rate) > 30:
        print(f"{county} has a higher that 30% vaccination rate")

print()
for county, rate in vacc_counties:
    if int(rate) > 30:
        print(f"{county} is doing ok, with a rate of {rate}%")
    else:
        print(f"{county} is doing less ok, with a rate of {rate}%")

相关问题 更多 >