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

标签 python list tuples

我正在尝试完成一项初学者作业,该作业需要引用列表中元组中的元素,该列表使用 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]"%")

最佳答案

备注:

  • 不要对变量名使用保留字,例如使用tpl而不是tuple
  • 删除元组中的for元素:循环
  • 要访问元组的第二个元素,请使用 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 - 不确定如何引用元组列表中元组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68537230/

相关文章:

python - emacs 上自动 header 的模板

python - 基于另一个列表中每个索引的值的列表组合

python - 在 python postgresql 列表中返回单列提取

c++ - 如何将 std::tuple 类型与 boost::mpl 算法一起使用?

object - 什么时候应该使用元组而不是对象,反之亦然?

python - 234 树蟒

java - 如何从 Java 启动独立、并发运行的 Python 进程

python - 总账并发(django原子操作)

python - 如何通过使用 Python 3 修剪前 3 个字母来打印两个列表的重叠值

python - 选择列表中下一个元组的命令