1

Considering having this type of lists:

month_list = ['Mar', 'Aug', 'Okt', 'Nov']
value_for_each_month = [4, 10, 8, 5]

So, each value belongs to the month in the month_list, e.g. 'Mar' --> 4, 'Aug' --> 10 and so on..

Now, how to fill both lists in Python to achieve this result:

month_list_new = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
value_for_each_month_new = [0, 0, 4, 0, 0, 0, 0, 10, 0, 8, 5, 0]
5
  • But, what is the criteria for the match. What is the logic with Mar pointing to 10 and Aug pointing to 8. This makes no sense. Commented Jul 22, 2017 at 12:40
  • Each index of the month_list matches the index in the value_for_each_month list. That is the criteria, I thought it was clear enough.. Commented Jul 22, 2017 at 12:41
  • You just changed your question to have it make sense now. It wasn't like that before. Commented Jul 22, 2017 at 12:43
  • Yeah, I had a Typo, sorry Commented Jul 22, 2017 at 12:43
  • Can you show your code to see what challenges your facing in your implementation? Commented Jul 22, 2017 at 12:44

1 Answer 1

2

Create a dictionary mapping month names to values...

>>> month_list = ['Mar', 'Aug', 'Okt', 'Nov']
>>> value_for_each_month = [4, 10, 8, 5]
>>> month_values = dict(zip(month_list, value_for_each_month))
>>> month_values
{'Aug': 10, 'Mar': 4, 'Nov': 5, 'Okt': 8}

... than use that dict in a list comprehension:

>>> month_list_new = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']    
>>> value_for_each_month_new = [month_values.get(m, 0) for m in month_list_new]
>>> value_for_each_month_new
[0, 0, 4, 0, 0, 0, 0, 10, 0, 0, 5, 0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.