简体   繁体   English

如何将普通的“打印”与“打印”分开?

[英]How do I separate a normal “print” from a “for print”?

Just going to get straight to the point, but when I write a normal "print" after writing a "for print" I only get the letter of the last word.只是要直截了当,但是当我在写完“for print”之后写一个普通的“print”时,我只得到最后一个单词的字母。 Here is what I wrote这是我写的

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animallist in animallist:
  print (animallist)

and when I write this当我写这个的时候

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animallist in animallist:
  print (animallist)
print(animallist[4])

It just goes and shows the list and the last letter of the last word.它只是显示列表和最后一个单词的最后一个字母。

So what im trying to make is a normal list with "chicken" at the bottom aswell.所以我想要做的是一个普通的列表,底部也有“鸡”。 Im not good with this so Im kinda clueless, would love some help, what im looking for is something that looks like我不擅长这个,所以我有点无能为力,希望得到一些帮助,我正在寻找的东西看起来像

Animal list:
cows
sheep
pigs
horses
chickens
goats
ducks

chickens

Understand the list and the item in the list:理解列表和列表中的项目:

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animal in animallist:
  print (animal)
print(animallist[4])

When python run the for loop, it re-assigns the variable animallist to each item of the animallist (class 'list') ("cows", "sheep", "pigs", etc. which are class 'str' ), so the variable animallist has become class 'str' .当python运行for循环时,它将变量animallist重新分配给animallist的每个项目animallist (class 'list') (“ animallist (class 'list') ”、“sheep”、“pigs”等属于class 'str' ),所以变量animallist已成为class 'str' When the for loop iterates to the last item of the list, which is "ducks" , it assigns animallist to the value "ducks" , so when it runs the print(animallist[4]) , it will print the 4th index of the string "ducks" , which is s .当 for 循环迭代到列表的最后一项,即"ducks" ,它将animallist分配给值"ducks" ,因此当它运行print(animallist[4]) ,它将打印该列表的第 4 个索引字符串"ducks" ,即s

You can see the type of your animallist variable has changed here:您可以在此处看到您的animallist变量的类型已更改:

animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
print(type(animallist))

for animallist in animallist:
    pass

print(type(animallist))

Output:输出:

<class 'list'>
<class 'str'>

So you shouldn't use the same name for the variable in the loop functions and the iterable.所以你不应该对循环函数和迭代中的变量使用相同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM