将元素从字符串数组输出到句子

时间:2019-06-17 15:35:03

标签: 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]

5 个答案:

答案 0 :(得分:2)

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

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]

答案 1 :(得分:1)

我将使用字典将一个映射到另一个,然后进行串联:

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

您可以在此处使用for循环,但是列表理解更简洁。

答案 2 :(得分:0)

text = ['a', 'bc', 'cab', 'x']
letters = ["a", "b", "c"]
names = ["Abby", "Bob", "Carl"]

d = {k: v for k, v in zip(letters, names)}
s = [(t, ''.join(d[c] for c in t if c in d)) for t in text]

for l, t in s:
    print('text =', l)
    print('output:', t)

打印:

text = a
output: Abby
text = bc
output: BobCarl
text = cab
output: CarlAbbyBob
text = x
output: 

答案 3 :(得分:0)

您可以这样做:

output = ''.join([names[i] for r in text for i in [ letters.index(r)]])
# or output = ''.join([names[letters.index(r)] for r in text])

礼物:

In [110]: letters = ["a", "b", "c"]
     ...: names = ["Abby", "Bob", "Carl"]
     ...:

In [111]: ''.join([names[i] for r in text for i in [ letters.index(r)]])
Out[111]: 'AbbyBobBob'

答案 4 :(得分:0)

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