【问题标题】:Python : How to increment element in a For loop of a list of strings? [duplicate]Python:如何在字符串列表的 For 循环中增加元素? [复制]
【发布时间】:2021-07-04 13:57:29
【问题描述】:

我是 python 新手,在查看课程时,我想到了一些我找不到解决方案的东西:

proteins = ["venison", "tuna", "chicken"]
veggies = ["kale", "spinach", "tomatoes"]

for i in proteins:
    for j in veggies:
        if j == "spinach":
            print("Spinach?!? Feed it to the dog")
    print(i,j)
print(type(j))

结果:

venison kale
Spinach?!? Feed it to the dog
venison spinach
venison tomatoes
tuna kale
Spinach?!? Feed it to the dog
tuna spinach
tuna tomatoes
chicken kale
Spinach?!? Feed it to the dog
chicken spinach
chicken tomatoes

我的意图是,而不是打印“鹿肉菠菜...”和肉和菠菜,实际上,是用句子(“菠菜?!?喂狗”)而不是打印“菜单” .

我的想法是, 每当j==spinach我们 print("Spinach?!? Feed it to the dog") 在这里我们转到下一个索引之前 print(i,j).

我该怎么做?

希望我的问题有意义! 谢谢,

【问题讨论】:

  • 您是否正确复制了缩进?我没有得到与您显示的相同的输出。
  • 如果print(i, j) 缩进另一个级别,我会得到该输出。
  • 你能描述一下你想要的输出吗?
  • edit您的帖子并添加您的预期输出

标签: python


【解决方案1】:

if 之外使用else,如下所示:

proteins = ["venison", "tuna", "chicken"]
veggies = ["kale", "spinach", "tomatoes"]

for i in proteins:
    for j in veggies:
        if j == "spinach":
            print("Spinach?!? Feed it to the dog")
        else:
            print(i,j)
print(type(j))

【讨论】:

    【解决方案2】:
    if j == 'Spinach':
      print(...)
      continue
    

    if j == 'Spinach':
       print("Feed it..")
    else:
       print(i,j)
    

    【讨论】:

      【解决方案3】:
      proteins = ["venison", "tuna", "chicken"]
      veggies = ["kale", "spinach", "tomatoes"]
      
      for i in proteins:
          for j in veggies:
              if j == "spinach":
                  print("Spinach?!? Feed it to the dog")
              else:
                  print(i,j)
      

      【讨论】:

        【解决方案4】:

        哈哈哈......就这么简单......傻了我^^' 可以变得复杂,为什么要变得简单?

        话虽如此,有没有办法以某种方式增加索引或元素?

        我试过了

        proteins = ["venison", "tuna", "chicken"]
        veggies = ["kale", "spinach", "tomatoes"]
        
        for i in proteins:
            for j in veggies:
                if j == "spinach":
                    print("Spinach?!? Feed it to the dog")
                    j=j+1
                print (I,j)
        

        但它返回一个错误: TypeError: 只能将 str(不是“int”)连接到 str。

        我知道 I 或 j 不是列表的索引...所以我想知道我该怎么做。

        谢谢大家!

        【讨论】:

          猜你喜欢
          • 2022-11-24
          • 2012-05-26
          • 2022-12-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多