FesteringDoubt FesteringDoubt - 2 years ago 100
Python Question

Python list string comparison not working

I'm trying to create a small python program that takes a list of first names and last names, creates a usernames in the format FirstInitial . LastName (optional number to differentiate similar names), example P.Test16. It then compares them to a list of existing usernames, as well as all other newly generated usernames and makes them all unique by incrementing the number on the end.
However while it can compare new usernames to existing usernames it can't compare them to other new usernames, for example I currently already have a user names "j.moore" and I also have tow new users who will have a usernames j.moore, so both have usernames "j.moore1" after the first run in the while loop, but it won't then make the second one "j.moore2" in the second run. below is my code

while len(intakearray) > 0:
nonuniqueusers = []
for row in intakearray:
if (row[2] not in usersarray) and (row[2] not in uniqueusers):
if count > 0:
if args.verbose >= 1:
conflicts += 1
if args.verbose == 2:
for row in nonuniqueusers:
newname = row[2]
if count >= 1:
newname = row[2][0:-1]
newname += str(count + 1)
row[2] = newname
intakearray = nonuniqueusers
count += 1

Answer Source

When a user is unique you store the complete row from the intakearray in uniqueusers (line 7 of your code listing):


However, when you check whether a user name is unique, you check whether the username in row[2] is in uniqueusers (line 4 in your code):

if (row[2] not in usersarray) and (row[2] not in uniqueusers):

When you change line 7 from uniqueusers.append(row) to uniqueusers.append(row[2]) your code should work as expected.

As your example does not says anything about the contents of the usersarray you should check that there is not the same mismatch between having full rows in there and checking only for the user name in the if-statement above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download