当打印列表 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/