I'm working on this program and I am currently stuck on this issue. I have been given a list of words and also a list of indices and I was wondering if anyone could help me write a simple function to join the list of words together in the order of the indices given. The first argument would be the list of words:
['boy', clown, 'a', 'saw']
The second argument would be the list of indices:
[2, 0, 3, 2, 1]
The expected outcome would be " a boy saw a clown". Any help is appreciated although Id prefer not using list comprehension and would rather go with a for loop with some combination of indexing for example.
CodePudding user response:
This is easily achieved with a list comprehension:
words = ['boy', 'clown', 'a', 'saw']
indices = [2, 0, 3, 2, 1]
results = [words[i] for i in indices]
CodePudding user response:
Using a for loop:
words = ['boy', 'clown', 'a', 'saw']
indices = [2, 0, 3, 2, 1]
output = []
for i in indices:
output.append(words[i])
print(' '.join(output))
CodePudding user response:
Using a function and a loop:
def get_line(words, indices):
line = ''
for i, index in enumerate(indices):
line = words[index]
if i != len(indices) - 1:
line = " "
return line
print(get_line(['boy', 'clown', 'a', 'saw'], [2, 0, 3, 2, 1]))
Output:
a boy saw a clown
Disclaimer:
The other two answers (list comprehensions and appending to a list) are better than this. I added this as an alternative solution.
