【问题标题】:How can I assign non-numerical Ids to list elements in Python?如何将非数字 ID 分配给 Python 中的列表元素?
【发布时间】:2022-08-24 17:30:40
【问题描述】:

我有一个字符串列表,我想为它们分配一个唯一的后缀作为 ID,如下所示:

假设列表是[\"str1\", \"str2\", \"str3\"],我想像这样插入ID:[\"str1-a\", \"str2-b\", \"str3-c\"].

有什么方法可以迭代地分配这些 id,例如:

id = a
for each element in the list:
    add the id to the string
    increment the id # from a to b, from b to c etc.

而不是按顺序排列每个元素并执行三遍?

谢谢!!

  • 如果超过 26 个字符串会发生什么?
  • 就我而言,我知道不会超过 26 个字符串。我想在这种情况下,我将不得不以某种方式组合这些字符。

标签: python string


【解决方案1】:

string 模块中有一个常量,它包含一个字符串中的所有字母,例如'abcdefg...'。请参阅docs

from string import ascii_lowercase
new_list = []
for letter, element in zip(ascii_lowercase, old_list):
    new_list.append(element + '-' + letter)

或者,使用列表推导:

new_list = [element + '-' + letter for letter, element in zip(ascii_lowercase, old_list)]

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 2018-07-17
    • 2020-05-06
    • 2019-01-14
    • 2020-06-22
    • 2019-08-28
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多