简体   繁体   中英

Unsure how to refer to elements in tuples in a list of tuples

I am trying to complete a beginner assignment that entails referencing elements in tuples in a list that uses for loops and conditionals to output one of two types of strings depending on the values in the tuples.

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%

Here is the list of tuples followed by my own code:

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]"%")

Remarks:

  • don't use reserved words for variable names, eg use tpl rather than tuple
  • remove the for element in tuple: loop
  • to access second element of tuple, use tpl[1] instead of [1]
  • use elif instead else

Corrected code:

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]}%")

Prints:

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%

You can let Python unpack the two values in each tuple into easy to use variables like this:

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}%")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM