【问题标题】:Does a for loop empty a list in Python?for 循环是否会清空 Python 中的列表?
【发布时间】:2020-04-21 15:29:16
【问题描述】:

如何将列表中的项目作为第二和第三部分的输出? (每次我想打印它们时,它们只打印列表中某个项目的字母。)

foods = ["pizza", "burger", "popcorn", "cannoli", "noodles"]
print("The foods I like are:\n")
for foods in foods[:3]:
    print(foods.title())
#2nd
print("The foods my friend likes are:\n")
for foods in foods[1:4]:
    print(foods.title())
#3rd
print("The food SHE likes are:\n")
for foods in foods[:]:
    print(foods.title())

【问题讨论】:

  • 当你为 foods in foods[:3] 做 for foods 时,你重新分配了 foods 的价值。试试这个方法。食物中的食物[:3]: print(food.title())

标签: python list for-loop


【解决方案1】:

您在每次迭代中覆盖foods。请试试这个:

foods = ["pizza", "burger", "popcorn", "cannoli", "noodles"]
#2nd
print("The foods my friend likes are:\n")
for f in foods[1:4]:
    print(f.title())
#3rd
print("The food SHE likes are:\n")
for f in foods[:]:
    print(f.title())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2014-10-31
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多