gpt4 book ai didi

python - 列表中每个元组的第一个元素与字母字符之间的高效映射

转载 作者:行者123 更新时间:2023-12-01 03:24:30 25 4
gpt4 key购买 nike

我有一个字符串元组列表:

lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]

我想在每个元组的第一个元素和英文字母小写字符之间创建映射:

  • 'first' 映射到 'a'
  • 'second' 映射到 'b'
  • 'third' 映射到 'c'
  • 'fourth' 映射到 'd'

我已经尝试过字典

dct = {'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

但我想知道是否有一种更有效的方法来创建包含元组第一个元素和字母表列表的列表,然后迭代它们以创建字典。

此外,对于字母字符,我尝试使用 string.ascii_lowercase 但它给出的字符串不是每个字符的列表。

我是 Python 新手,所以如果上面的问题很基本,请原谅。如果有任何示例代码可供我理解和学习,我将不胜感激。

最佳答案

您可以使用zip()和一本字典comprehension :

>>> from string import ascii_lowercase
>>> lst = [('first', 'one'), ('second', 'two'), ('third', 'three'), ('fourth', 'four')]
>>> {x[0]: y for x, y in zip(lst, ascii_lowercase)}
{'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

或者如果您想以更“实用”的方式进行操作:

>>> from operator import itemgetter
>>> {x: y for x, y in zip(map(itemgetter(0), lst), ascii_lowercase)}
{'first': 'a', 'second': 'b', 'third': 'c', 'fourth': 'd'}

关于python - 列表中每个元组的第一个元素与字母字符之间的高效映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41520471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com