python - 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.
解决方案
最好是用字典来做到这一点。
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"]
推荐阅读
- xslt - 关于 xsl:try xsl:catch 中的错误信息的问题
- r - 在 R 中,有没有办法减少连续日期 x 轴上的刻度数?
- python - 错误列表索引必须是整数,但只要我不使用输入来获取参数它就可以工作
- html - 如何使用 CSS 为整个 HTML 网页设置字体大小?
- javascript - 如何保存和恢复相机配置
- git - Git GUI 推送到特定的 refs 命名空间
- python - 有没有办法将 h2oframe 转换为 pandas 数据帧
- security - 如何在 oauth2 身份验证之上实现用户权限
- javascript - 异步映射返回 Promise
- gnuplot - Gnuplot 错误消息:未定义变量通过