vectorizinglife
vectorizinglife

Reputation: 97

Output elements from a string array to a sentence

The code should output string elements from list B when printing something from list A.

Say we have

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

How to iterate through the lists so when text is updated to

text = "a"
output: Abby

text = "ab"
output: "AbbyBob

text = "cab"
output: "CarlAbbyBob"

I have tried thinking about an if statement inside a foor loop but cannot really figure it out. I have simplified the problem to three elements for this post but the list has 30 elements, hence the for loop would be a good idea.

My try

text = ""

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

Upvotes: 0

Views: 1467

Answers (5)

Jkind9
Jkind9

Reputation: 740

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

Set up a dictionary:

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

Then create a loop for your string

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


>>>>AbbeyBobCarl

Upvotes: 0

Ayoub ZAROU
Ayoub ZAROU

Reputation: 2417

You may do :

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])

Gives :

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'

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

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)

Prints:

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

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

I would use a dict to map one to the other, and then do concatenation:

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

You could use a for loop here, but list comprehension is cleaner.

Upvotes: 1

static const
static const

Reputation: 943

You can use a dict to map letter to the name

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]

Upvotes: 2

Related Questions