Home > Blockchain >  Python3 find position/index of a name/element in a list with more than one of the same name
Python3 find position/index of a name/element in a list with more than one of the same name

Time:12-03

I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once.

lst = ['hello.com', 'hello.com', 'hello.com', 'world.com', 'test1.com']
index = web_lst.index(domain) 1
print(index)

The issue with this code is that index() will always find and use the first 'hello.com' instead of any of the other "hello.com's", so index will always be 1. If I were asking for any of the other names then it'd work I think.

I am trying to get the integer representation of the 'hello.com' names (1, 2, 3, etc.), and I don't know how to do that or what else to use besides python lists. This, I don't think is going to work and I'm asking for any other ideas on what to do or use instead of using a list. (if what I'm trying to do is not possible with lists)



My main goal is basically a login manager using sqlite3 and I want to have the ability to have multiple logins with some having the same domain name (but with different data and notes, etc.), because we like to have multiple logins/accounts for 1 website. I have a TUI (beaupy) for selecting the domain/option you want to get the login for but if you have more than 1 of the same domain name it doesn't know which one to pick. I have managed to use integers as IDs in the sqlite3 database to help but the main issue is the picking of an element from a list to get a number, to then plug into the read() function. So the list options will correlate to the "IDs" in the database. List index 0 1 would be option/row 1 in the database (and so on).

def clear():
    os.system('clear||cls')


def add(encrypted_data):
    ID = 1
    database = sqlite3.connect('vault.gter')
    c = database.cursor()

    #Check to see if IDs exist and if yes then get how many/length of list and add 1 and use that instead.
    c.execute("SELECT id FROM logins")
    all_ids = c.fetchall()
    out = list(itertools.chain(*all_ids))
    list_length = len(out)
    if not all_ids:
        pass
    else:
        for x in out:
            if x == list_length:
                ID = x 1
            else:
                pass

    c.execute(f"INSERT INTO logins VALUES ('{ID}', '{encrypted_data}')")
    database.commit()
    database.close()




def domains(dKey):
    database = sqlite3.connect('vault.gter')
    c = database.cursor()
    c.execute("SELECT data FROM logins")
    websites = c.fetchall()
    enc_output = list(itertools.chain(*websites))

    web_lst = []
    note_lst = []
    for x in enc_output:
        result = gcm.stringD(x, dKey) #decrypt encrypted json string.
        obj_result = json.loads(result) #turns back into json object
        website = obj_result['Domain']
        notes = obj_result['Notes']
        web_lst.append(website)
        note_lst.append(notes)

    for w,n in zip(web_lst, note_lst):
        with open('.lst', 'a') as fa:
            fa.writelines(f"{w}  ({n})\n")
            fa.close()


    with open(".lst", "r ") as fr:
        data = fr.read()
        fnlst = data.strip().split('\n')
        fr.truncate(0)
        fr.close()

    os.remove(".lst")
    print(f'(Press "ctrl c" to exit)\n-----------------------------------------------------------\n\nWebsite domain/name to get login for?\n')
    domain = beaupy.select(fnlst, cursor_style="#ffa533")

    clear()
    if domain == None:
        clear()
        return
    else:
        domain = domain.split(' ', 1)[0] #get first word in a string.
        print(domain) #debug
        index = web_lst.index(domain) 1
        input(index) #debug

        pwd = read(index)
        return pwd




# Come up with new way to show available options to chose from and then get number from that to use here for "db_row".
def read(db_row):
    database = sqlite3.connect('vault.gter')
    c = database.cursor()

    c.execute("SELECT id FROM logins")
    all_ids = c.fetchall()
    lst_output = list(itertools.chain(*all_ids))

    if not all_ids:
        input("No IDS") #debug
        database.commit()
        database.close()
        return
    else:
        for x in lst_output:
            if x == db_row:
                c.execute(f"SELECT data FROM logins WHERE id LIKE '{db_row}'") #to prevent my main issue of it not knowing what I want when two domain names are the same.
                stoof = c.fetchone()
                database.commit()
                database.close()
                return stoof[0]
            else:
                #(debug) - input(f"error, x is not the same as db_row. x = {x} & db_row = {db_row}")
                pass


If anyone has a better way of doing this whole login manager thing, I'll be very very appreciative. From handling the database and sqlite3 commands, better IDs? to perhaps completely a different (and free) way of storage. And finding a better way to handle my main problem here (with or without having to use lists). Anything is helpful. <3

If anyone has questions then feel free to ask away and I'll respond when I can with the best of my knowledge.

CodePudding user response:

Here is a one-liner:

[{item:[i for i, x in enumerate(lst) if x == item]} for item in set(lst)]

CodePudding user response:

You can get both the index and the element using a for-loop.

for i in range(len(lst)):
    element = lst[i]
    if element == domain:
        print(i)

This should give you all indexes of domain.

Edited Code:

d = {}
c = 0
for i in range(len(lst)):
    element = lst[i]
    if element == domain:
        c  = 1
        d[c] = i

c is the occurence number, and i is the index.

  • Related