简体   繁体   English

为什么下面的代码不产生任何 output?

[英]Why doesn't the code below produce any output?

There are two code snippets, the upper one works but the lower one does not.有两个代码片段,上一个有效,而下一个无效。 Why doesn't second code snippet output anything?为什么第二个代码片段 output 什么都没有?

#This code works:
x=["Decomplete asd"]
y=[]
z=[]
for i in x:
    if "De" in i:
        y.append(i)
        print(y)
    if "comp" in i:
        z.append(i)
        print(z)

# This one does not:
x=["Decomplete asd"]
y=[]
z=[]
if "De" in x:
    y.append(x)
    print(y)
if "comp" in x:
    z.append(x)
    print(z)

welcome Nicathus !欢迎尼卡萨斯!

That's because X is a list that contains one string.那是因为 X 是一个包含一个字符串的列表 But x is not a string itself.但是 x 本身并不是一个字符串。

So:所以:

  • in the first case, i takes the value of each item in this list (as this list's lenght = 1, the loop will be quickly done).在第一种情况下,我获取此列表中每个项目的值(因为此列表的长度 = 1,循环将很快完成)。 So when i = "Decomplete asd", which is a string , the conditions are true: "De" and "comp" are in this string.所以当 i = "Decomplete asd",它是一个字符串时,条件为真: "De" 和 "comp" 在这个字符串中。

  • in the second case, the conditions apply directly to x.在第二种情况下,条件直接适用于 x。 And x is a list, not a string. x 是一个列表,而不是一个字符串。 It means that you're looking for the strings "De" and "comp" in a list that does not contain them, as items.这意味着您正在一个不包含它们的列表中寻找字符串“De”和“comp”作为项目。

It would work if you had x = ["De", "comp", "hello"] for instance.例如,如果您有x = ["De", "comp", "hello"] ,它将起作用。

Or if you had x = "Decomplete asd" (ie a string, without [ and ] ).或者如果你有x = "Decomplete asd" (即一个字符串,没有[] )。

Hope it helped !希望它有所帮助!

The code below the for loop checks for the de sired only once. for 循环下面的代码只检查一次所需内容。

The code adds each string on every instance.该代码在每个实例上添加每个字符串。 Basically, the top code doesn't stop looking until the code goes through every part of the collection.基本上,在代码遍历集合的每个部分之前,顶级代码不会停止查找。

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

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