-->

Divide elements of a list by integer with list com

2020-04-10 03:39发布

问题:

I am trying to divide all the elements of a list filled with integers by another integer (functionality like in numpy arrays) by list comprehension, like so:

results = 300 * [0]
for i in range(100):
    for j in range(300):
        results[j] += random.randrange(0,300)
average_results = [results[x] / 100 for x in results]

However, if I run this in Python, it throws an

IndexError: list index out of range

I have worked around this by using a regular for loop:

average_results = []
for x in results:
    average_results.append(x/100)

which works like a charm.

However, in my mind the two approaches should yield the same results, so I am totally stunted as to why it does not work.

Can someone point me in the right direction?

回答1:

The problem is with:

  [results[x] / 100 for x in results]

Here you are iterating over values in the results list (for x in results). And then for each of them trying to access the element with this index. What you rather meant was:

 [x / 100 for x in results]

In other words - the "for ... in ..." part of list comprehension works with values in the list, not their indices.

BTW, your [x / 100 for x in results] won't give you an average of all values. It will "only" take each of them and divide by 100.



回答2:

This is the equivalent list comprehension to your loop:

average_results = [x / 100 for x in results]

x is already the value form results. Don't index again into it with results[x].



回答3:

Your array is filled with random integer values, ranging from 0 to 29999. In your list comprehension you make, as far as I can see, a mistake here:

results[x]

x is already the value in the array, i.e. the random integer. You get the IndexError because results[29999] is, for example, one of the possible calls there.

What you want instead is to not use x as an index:

average_results = [x / 100 for x in results]


回答4:

you can use one of these at the end:

1. average_results = [results[x] / 100 for x in range(len(results))]
2. average_results = [x / 100 for x in results]

the problem is you're trying to access to an index that does not exist (x is the value there not the index)



回答5:

This should be straight forward and possible.

In [1]: results = 10 * [10]

In [2]: [_/10 for _ in results]
Out[2]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]