简体   繁体   中英

Why doesn't this string append with a for loop work?

I want to make a for loop that checks if list d has elements from list ident and if they don't, I want to add them. When I run this code part by part it works, but I suspect my False statement is not working, because it just doesn't append.

import pandas as pd
ident=['bla','me','you']
d=['bla']
for x in range(len(ident)):
    if ident[x] in d == False:
        d.append(ident[x])

Here is how I want the output to be:

d=['bla','me','you']

There might be a duplicate for this that I can't find, but just to explain the problem:

Python comparison operators chain . That is why you can write 1 < 2 < 3 < 4 in Python and it will evaluate as (1 < 2) and (2 < 3) and (3 < 4) .

By the same mechanism, when you write

if ident[x] in d == False:

it is broadly equivalent to

if (ident[x] in d) and (d == False):

Most of the time if you're tempted to write == False or == True , there's probably a better way to express the condition.

In this case, it should be:

if ident[x] not in d:

I understand that you didn't ask that. But let me try to optimize your code a bit. Because these two lists could have equal length and the search could be very long - up to O(n^2). So here are my small improvements that will allow you to make the full algorithm in O(n) time + fixing your error.

ident=['bla','me','you']
new_ident = dict(zip(ident, ident))
d=['bla']
for i in d:
    if i not in new_ident: new_ident[i] = True
ident = new_ident.keys()

This should produce the expected output.

 for x in range(len(ident)): if ident[x] not in d: d.append(ident[x])

merge = d + list(set(ident) - set(d)) + list(set(d) - set(ident))

it is different way

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