【问题标题】:Lists and indices in PythonPython 中的列表和索引
【发布时间】:2021-10-12 08:57:46
【问题描述】:

我有一个清单:

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]

我可以通过它们的位置访问每个食物并打印一些东西,如下所示:

"You do have food, your options are {} or {} or {} or {}".format(
    food_list[0], food_list[1],  food_list[3], food_list[4]
)

(不包括最后一项:'食用油')

但是,如果以任何方式更改列表的长度,则会出现索引(超出范围)错误。

如果列表长度发生变化,我如何获取列表中的项目,将它们放在上面的句子中而不会出现任何错误?

【问题讨论】:

  • 只有在列表中的项目少于四个时才会出现错误 - 在这种情况下您希望做什么
  • 您需要以某种方式遍历所有您想要的项目。你研究过迭代吗?

标签: python list indexing


【解决方案1】:

您可以在一行中完成此操作。例如

food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
"You do have food, your options are {}".format(" or ".join(food_list[:-1]))

输出:

你有食物,你的选择是鸡肉或混合蔬菜或蔬菜或豆类或玉米

ps:这也将排除列表中的最后一个食物。

【讨论】:

  • 我认为这个答案就是解决方案。
【解决方案2】:

尝试使用:

options = " or ".join(food_list)

【讨论】:

  • 很酷,但我想要除了最后一个食物之外的整个列表,所以我想我可以使用....food_list[:-1] ...我猜
【解决方案3】:

在这里,您想使用类似简单的 for 循环的东西:

string = "You do have food, your options are "
for food in food_list:
   string += food + " or "
string = string[:-3]
print(string)

在这里,您删除最后几个字符以删除最后一个“或”,同时动态添加列表中的每个项目。

【讨论】:

    【解决方案4】:

    TL;DR

    food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
    "You do have food, your options are {}".format(" or ".join(food_list))
    

    有很多方法可以满足您的要求。

    加入

    join,将容器中的每个元素连接成一个字符串:

    ",".join(["mohammad", "Shameoni", "Niaei"])
    #'mohammad,Shameoni,Niaei'
    

    循环

    您可以轻松地循环遍历可迭代对象并将它们附加到字符串中。

    my_string = ""
    for element in ["mohammad", "Shameoni", "Niaei"]:
        my_string += element + ","
    
    my_string = my_string[:-1]
    #'mohammad,Shameoni,Niaei'
    

    使用上述之一。

    【讨论】:

      【解决方案5】:

      尝试使用 fstring。

      food_list=["chicken", "mixed veggies", "greens", "beans", "corn", "cooking oil"]
      print(f"You do have food, your options are {food_list[0]} or {food_list[1]} or {food_list[3]} or {food_list[4]}")
      

      【讨论】:

        猜你喜欢
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 2012-08-09
        • 2019-07-05
        相关资源
        最近更新 更多