0

I'm trying to work through my first Python program (I just began taking a class for Python a month or so ago). Right now, I'm only allowed to use the standard library, but I can import the random library as well.

What I'm trying to do is compare two lists. One, is a list of random numbers (which I already have figured out) and the second one is a list of 1's and 0's. 1 meaning that the number in the first list needs to be replaced with a new random number. 0 Meaning they want to keep that number.

Could someone help me out and kind of explain their logic through it? I'm at a loss right now, and would really appreciate any help you could give me.

Here's what I have so far:

def replaceValues(distList, indexList):
    for i in range (1,len(indexList)):
         if indexList[i] = int(1):

Then I get kind of lost.

Thanks!

2
  • 1
    What have you tried so far? And, are both lists inputs, or do you have to generate them? Commented Feb 26, 2014 at 13:56
  • @JoanSmith Honestly, I'm kind of lost, even if just a starting point would be great. And both lists are input lists. Commented Feb 26, 2014 at 13:59

1 Answer 1

4

Use enumerate. It lets you iterate on a list with an index:

import random

control_list = [1, 0, 1]  # Your 0's and 1's
numbers_list = [1, 2, 3]  # Your random numbers


for index, control in enumerate(control_list):
    if control == 0: 
        numbers_list[index] = random.random()

print numbers_list
# [1, 0.5932577738017294, 3]

Note that this will replace the elements in numbers_list. If that's not desirable, you can create a new list and use zip, which lets you iterate over two lists in parallel:

import random

control_list = [1, 0, 1]
numbers_list = [1, 2, 3]

new_list = []
for control, number in zip(control_list, numbers_list):
    if control == 0:
        number = random.random()
    new_list.append(number)

print new_list
# [1, 0.46963935996528683, 3]

And in a single line, using a list comprehension:

l = [n if c == 1 else random.random() for n, c in zip(numbers_list, control_list)]
print l
# [1, 0.9579195229977218, 3]
Sign up to request clarification or add additional context in comments.

2 Comments

when I run the top program, I receive an error that list indices must be integers and not tuple. Can you tell me what I'm doing wrong?
@user3288734 Did you forget the , control part? You probably made a mistake copying the code.

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.