简体   繁体   English

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

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

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

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.我正在尝试获取“hello.com”名称(1、2、3 等)的 integer 表示,但我不知道该怎么做,也不知道除了 python 列表之外还能使用什么。 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.我的主要目标基本上是一个使用 sqlite3 的登录管理器,我希望能够进行多次登录,其中一些具有相同的域名(但具有不同的数据和注释等),因为我们希望有多个登录/帐户1 个网站。 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.我有一个 TUI (beaupy) 用于选择您想要登录的域/选项,但如果您有超过 1 个相同的域名,它不知道选择哪个。 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.我已经设法在 sqlite3 数据库中使用整数作为 ID 来提供帮助,但主要问题是从列表中选择一个元素来获取数字,然后插入 read() function。因此列表选项将与数据库中的“ID”。 List index 0+1 would be option/row 1 in the database (and so on).列表索引 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


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?从处理数据库和 sqlite3 命令,更好的 ID? 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 <3

If anyone has questions then feel free to ask away and I'll respond when I can with the best of my knowledge.如果有人有任何问题,请随时提问,我会尽我所知作出答复。

You can get both the index and the element using a for-loop.您可以使用 for 循环获取索引和元素。

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

This should give you all indexes of domain .这应该给你domain的所有索引。

Edited Code:编辑代码:

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 is the occurence number, and i is the index. c是出现次数, i是索引。

Here is a one-liner:这是一个单行:

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

暂无
暂无

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

相关问题 当存在多个具有相同 class 名称的元素时,如何通过具有 class 名称的 webdriver 查找元素? - how to find element by webdriver with class name when there are more than one element with the same class name? 根据一个以上的部分字符串并使用 python 中的运算符在列表中查找索引 position - Find index position in list based on more than one partial string and using operator in python 如何将list.index()(或类似文件)应用于多个列表以查找一对的位置? - How to apply list.index() (or similar) to more than one lists to find position of a pair? Selenium Python3 - 无法按名称找到元素 - Selenium Python3 - Unable to find element by its name 如何在numpy花式索引(索引列表中有多个相同的索引)中进行逐元素运算符(减)? - how to do element-wise operator(substract) in numpy fancy index(more than one same index in index list)? Python Pandas Dataframe:如何同时将 append 索引到多个列表? - Python Pandas Dataframe: How to append more than one index to a list at the same time? 在python中提取key_value,在csv中有多个同名列 - extracting key_value in python with more than one column with same name in csv 当您有多个同名类时,在 python 中抓取 html - Scraping html in python when you have more than one class with the same name 使用python读取HDF4文件 - 多个具有相同名称的数据集 - reading HDF4 file with python - more than one dataset with same name 尝试在同一索引处添加多个列表的元素 - Trying to add elements at the same index for more than one list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM