简体   繁体   中英

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?

#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. But x is not a string itself.

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). So when i = "Decomplete asd", which is a string , the conditions are true: "De" and "comp" are in this string.

  • in the second case, the conditions apply directly to x. And x is a list, not a string. It means that you're looking for the strings "De" and "comp" in a list that does not contain them, as items.

It would work if you had x = ["De", "comp", "hello"] for instance.

Or if you had x = "Decomplete asd" (ie a string, without [ and ] ).

Hope it helped !

The code below the for loop checks for the de sired only once.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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