将字符串数组中的元素输出到senten

2024-04-24 12:09:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 字符串代码text文本元素内容列表for
3条回答

https://www.w3schools.com/python/python_dictionaries.asp

设置词典:

thisdict =  {
  "a": "Abbey",
  "b": "Bob",
  "c": "Carl"
}

然后为字符串创建一个循环

string= 'abc'
''.join(thisdict[char] for char in string)


>>>>AbbeyBobCarl

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

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]

我会使用dict将一个映射到另一个,然后进行连接:

dct = dict(zip(letters, names))  # {"a": "Abby", ...}
...
text = input()
output = ''.join(dct[char] for char in text)
print(output)

您可以在这里使用for循环,但是列表理解更清晰。你知道吗

相关问题 更多 >