python:如何在字符串列表的for循环中增加元素?

des4xlb0  于 2021-07-14  发布在  Java
关注(0)|答案(4)|浏览(291)

我是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) .
我该怎么做?
希望我的问题有道理!谢谢您,

gab6jxml

gab6jxml1#

if j == 'Spinach':
  print(...)
  continue

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

unhi4e5o2#

使用 else 除了 if ,如下所示:

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))
xwbd5t1u

xwbd5t1u3#

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)
u2nhd7ah

u2nhd7ah4#

哈哈哈。。。和其他一样简单。。。愚蠢的我^ ^既然你能让事情变得复杂,为什么还要让事情变得简单?
也就是说,是否有一种方法可以以某种方式增加索引或元素?
我试过了

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不是列表的索引。。。所以我想知道我该怎么做。
谢谢大家!

相关问题