繁体   English   中英

Python3 在具有多个相同名称的列表中查找名称/元素的位置/索引

[英]Python3 find position/index of a name/element in a list with more than one of the same name

我有一个问题,我只是不知道如何解决,而且我发现的任何东西都没有帮助。 我的问题是我有一个名称(字符串)列表,在这个列表中我将多次出现相同的名称。

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

此代码的问题是 index() 将始终查找并使用第一个“hello.com”而不是任何其他“hello.com”,因此索引将始终为 1。如果我要求任何其他名字然后我认为它会起作用。

我正在尝试获取“hello.com”名称(1、2、3 等)的 integer 表示,但我不知道该怎么做,也不知道除了 python 列表之外还能使用什么。 这个,我认为不会起作用,我正在询问关于做什么或使用而不是使用列表的任何其他想法。 (如果列表无法实现我想要做的事情)



我的主要目标基本上是一个使用 sqlite3 的登录管理器,我希望能够进行多次登录,其中一些具有相同的域名(但具有不同的数据和注释等),因为我们希望有多个登录/帐户1 个网站。 我有一个 TUI (beaupy) 用于选择您想要登录的域/选项,但如果您有超过 1 个相同的域名,它不知道选择哪个。 我已经设法在 sqlite3 数据库中使用整数作为 ID 来提供帮助,但主要问题是从列表中选择一个元素来获取数字,然后插入 read() function。因此列表选项将与数据库中的“ID”。 列表索引 0+1 将是数据库中的选项/行 1(依此类推)。

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


如果有人有更好的方法来完成整个登录管理器的事情,我将非常感激。 从处理数据库和 sqlite3 命令,更好的 ID? 也许是完全不同的(免费的)存储方式。 并在这里找到一种更好的方法来处理我的主要问题(使用或不使用列表)。 任何事情都是有帮助的。 <3

如果有人有任何问题,请随时提问,我会尽我所知作出答复。

您可以使用 for 循环获取索引和元素。

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

这应该给你domain的所有索引。

编辑代码:

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

for number, index in d.items():
    # Do something here. Remember to use number and index instead of c and i!

c是出现次数, i是索引。

这是一个单行:

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

暂无
暂无

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

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