1

Firstly, I'm a python beginner and just stuck at simple thing.

I want to replace some of my elements in a list with randomly created numbers (by index), according to my values in another list.

Expected output will be like: [3,2,2,1,3]

My code at below totally doesn't work in the way it should.

ori = [4,1,2,1,3]   # some elements inside need to be changed 
num_list = [2,1,1,1]    # numbers that represent index in ori

import random
for num in range(len(num_list)):
    ori[num-1]= random.randint(1,4)
    # I want to replace element with previous one from given index                                                                           
print(ori)

5
  • 1
    Why the range(len( if num_list is already the indices to modify? Probably you should not allow duplicate indices in num_list as well (e.g. use a set instead of a list) Commented Sep 29, 2019 at 14:43
  • Why index 1 is mentioned 3 times? How can you have expectations about the output of you use random? Commented Sep 29, 2019 at 14:45
  • Erm...I mean to go through every item in num_list to get the values for modifying Commented Sep 29, 2019 at 14:49
  • I think you mean ‘for num in num_list:’ Commented Sep 29, 2019 at 14:51
  • The value 1 is duplicated, and it should take only one of them for modifying. The expected output I give is just an example, just to mention that I want [0] and [1] value to be changed Commented Sep 29, 2019 at 14:55

2 Answers 2

2

I don't know what you want to do but it seems to be good with this code. Why num_list contain number "1" 3 times ? In this code it will replace ori[1] by a random number 3 times... Ok for ori[2] will be randomized one time.

ori = [4,1,2,1,3]   # some elements inside need to be changed 
num_list = [2,1,1,1]    # numbers that represent index in ori

import random
for num in num_list:
    ori[num]= random.randint(1,4)
print(ori)
Sign up to request clarification or add additional context in comments.

Comments

0

The problem you have is that the num variable you declare is just the position in num_list, so here you will change ori at positions 0, 1, 2, 3 (which is what will be represented by your range).

You would fix your code like this:

ori = [4,1,2,1,3]   # some elements inside need to be changed 
num_list = [2,1,1,1]    # numbers that represent index in ori

import random
for num in num_list:
    ori[num-1]= random.randint(1,4)

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.