首页 > 解决方案 > How to connect two list together in python

问题描述

I have these two list:

names = ["John", "Barack", "Elon"]
numbers = ["0342", "03478878", "0345"]

They are my clients, what I want is that the item "John", should be linked with its number, which is the 0 position item in the list, and so on, I also want to link the other names with there numbers respectively,so like when I export them later into a sqlite database the number "0342" should be below John, and so on with rest of names.

标签: pythonpython-3.xlistsqlite

解决方案


最好是用字典来做到这一点。

dct = {name: number for name, number in zip(names, numbers)}

正如@Onyambu 指出的那样,这也适用于

dct = dict(zip(names,numbers))

从右到左阅读此列表表达式: zip()将列表中的每个第 i 个元素相互配对。它们分别分配给每对,name然后number将它们作为key: value对收集到字典{} 中,然后分配给dct

您可以通过以下方式获得每个名称的编号:

dct["John"] ## "0342"
for name in names:
    print(dct[name])

如果“约翰”有更多条目

如果有更多条目,上面的代码将覆盖以前的 John 值。在这种情况下

def to_dict(l1, l2):
    dct = {}
    for key, val in zip(l1, l2):
        dct[key] = dct.get(key, []) + [vak]
    return dict

这可确保每个名称的所有值都收集在列表中。 dct.get(key, [])是一个很好的技巧,因为 if 会查看 是否key是 中的键dct,如果不是,则返回[]- 所以这保证了列表融合的组合,+ [number]最后你保证了列表中的一个或多个数字。

names = ["a", "b", "c", "a", "b", "d"]
numbers = [1, 4, 2, 4, 5, 5]

name2numbers = to_dict(names, numbers)

name2numbers["a"] ## [1, 4]
name2numbers["d"] ## [5]

要从值到名称搜索,只需翻转函数中的列表

number2names = to_dict(numbers, names)


number2names[4] ## ["b", "a"]
number2names[2] ## ["c"]

推荐阅读