python - 将字符串数组中的元素输出到句子

标签 python string list

当打印列表 A 中的内容时,代码应输出列表 B 中的字符串元素。

假设我们有

text = ""
letters = ["a", "b", "c"]
names = ["Abby", "Bob", "Carl"]

如何遍历列表以便当文本更新为

text = "a"
output: Abby

text = "ab"
output: "AbbyBob

text = "cab"
output: "CarlAbbyBob"

我曾尝试在 foor 循环中考虑 if 语句,但无法真正弄明白。对于这篇文章,我已将问题简化为三个元素,但该列表有 30 个元素,因此 for 循环是个好主意。

我的尝试

text = ""

for i in text:
    if i == letters[letters ==i]:
        text = text + names[i]

最佳答案

您可以使用字典将字母映射到名称

letter_to_name = dict()

for idx, val in enumerate(letters):
    letter_to_name[val] = names[idx]

#Creates are mapping of letters to name

#whatever is the input text, just iterate over it and select the val for that key

output = ""
for l in text:
    if l not in letter_to_name:
        #Handle this case or continue
    else:
        output += letter_to_name[l]

关于python - 将字符串数组中的元素输出到句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634568/

相关文章:

c# - 列表的交集

python - 检查 2 个列表之间的部分匹配

python - 从字符串中剥离注释行

java - 在 Java 中重复一个字符串——类似于 Python 的一行简单性

javascript - 如何使用 JavaScript 重建字符串

python - (初学者)NLP :I am trying to understand how I can categorise words in text to identify all the words related to a topic

java - 从作为 Map<String,List<Object>> 一部分的 List<Object> 中删除值

python - 将 mimetypes.guess_type 与 email.mime.base.MIMEBase 一起使用

python - random.randint 生成加密安全 key

python - Reportlab - 饼图填充颜色