Hugh Smith
Hugh Smith

Reputation: 35

How do i convert numbers to the words assigned in this program?

This is a program where a list of numbers has to be converted to a list of words, by position in a list. For instance:

numbers = [1, 2, 1, 3, 2, 4, 1 ,5] #Input from user this is an example
words = ["apple", "pear", "lemon", "grape", "pineapple"] 

The numbers in the "numbers" list are the indices of each item in the "words" list. This output of this scenario should be:

apple pear apple lemon pear grape apple pineapple

Keep in mind that this is just an example; these lists will be taken from a text file.

Here is the part that I am stuck at:

for i in numbers: #i for the loop
    match = re.match(words.index[i], numbers)
    if match:
        numbers = words #I have no clue here
print(numbers)

This is just an extract from my program that needs some work done to it so the variables are correct.

Upvotes: 0

Views: 116

Answers (4)

kouty
kouty

Reputation: 320

  numbers = [1, 2, 1, 3, 2, 4, 1 ,5]  # Input from user. This is an example
  words = ["apple", "pear", "lemon", "grape", "pineapple"] 

  for i in range(len(numbers)):
      numbers[i] = words[numbers[i] - 1]

  print numbers

Upvotes: 0

Uriel
Uriel

Reputation: 16204

Use mapping instead of unnecessary regex:

>>> numbers = [1, 2, 1, 3, 2, 4, 1 ,5] #Input from user this is an example
>>> words = ["apple", "pear", "lemon", "grape", "pineapple"]
>>> list(map(lambda x: words[x - 1], numbers))
['apple', 'pear', 'apple', 'lemon', 'pear', 'grape', 'apple', 'pineapple']

In human words, it means, map every number in the array numbers to its index at words lower by - 1 to get a 0-based indexing.

You could gain the same result using

>>> [words[index - 1] for index in numbers]
['apple', 'pear', 'apple', 'lemon', 'pear', 'grape', 'apple', 'pineapple']

Upvotes: 4

Prune
Prune

Reputation: 77850

You need to iterate through the list of numbers. For now, use a for loop:

for index in numbers:

Inside that loop, you need to find the word matching that index:

    word = words[index-1]

... and then simply print the word.

ADVANCED

There are ways to put this into one line; I'm sure others will how you list comprehensions and join or map operations, such as the code below. Pick your own comfort level for now.

print ' '.join([words[index-1] for index in numbers])

This is more "Pythonic" ... but learn at your own pace.

Upvotes: 2

DYZ
DYZ

Reputation: 57085

Very advanced, potentially much more powerful that ever necessary:

import numpy as np
words = np.array(["apple", "pear", "lemon", "grape", "pineapple"])
numbers = np.array([1, 2, 1, 3, 2, 4, 1 ,5])
words[numbers - 1].tolist()
# ['apple', 'pear', 'apple', 'lemon', 'pear', 'grape', 'apple', 'pineapple']

Upvotes: 2

Related Questions