如何使用给定words、definitions列表构建名为cooldictionary的键值字典
代码实现方案
Python中可以直接通过内置zip()函数配对两个列表的同位置元素,再转换为字典即可完成需求,具体代码如下:
# 给定的示例列表 words = ["PoGo","Spange","Lie-Fi"] definitions = ["Slang for Pokemon Go","To collect spare change, either from couches, passerbys on the street or any numerous other ways and means","When your phone or tablet indicates that you are connected to a wireless network, however you are still unable to load webpages or use any internet services with your device"] # 生成目标字典 cooldictionary = dict(zip(words, definitions))
验证说明
你可以执行打印代码查看生成的字典内容:print(cooldictionary)
输出结果如下:
{'PoGo': 'Slang for Pokemon Go', 'Spange': 'To collect spare change, either from couches, passerbys on the street or any numerous other ways and means', 'Lie-Fi': 'When your phone or tablet indicates that you are connected to a wireless network, however you are still unable to load webpages or use any internet services with your device'}
示例词汇中文释义
- PoGo:宝可梦GO的俚语说法
- Spange:指通过翻沙发缝隙、向街上路人讨要等各类途径收集零钱的行为
- Lie-Fi:指手机或平板显示已连接无线网络,但实际上无法加载网页、使用任何联网服务的情况
注意事项
该方案默认words和definitions两个列表长度完全一致,若实际场景中两个列表长度不等,zip()函数会自动以长度更短的列表为准完成配对,超出的元素会被忽略。
内容的提问来源于stack exchange,提问作者Haspdecrypted
相关产品推荐
相关产品推荐

