用列表理解将列表的元素除以整数:索引超出范围 [英] Divide elements of a list by integer with list comprehension: index out of range

查看:116
本文介绍了用列表理解将列表的元素除以整数:索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过列表理解力将用整数填充的列表的所有元素除以另一个整数(功能类似于numpy数组),例如:

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]

但是,如果我在Python中运行它,则会抛出一个

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

IndexError: list index out of range

我通过使用常规的for循环来解决此问题:

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?

推荐答案

问题出在:

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

这里您要遍历结果列表(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]

换句话说,列表理解的"for ... in ..."部分适用于列表中的值,而不是其索引.

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

BTW ,您的[x / 100 for x in results]不会为您提供所有值的平均值.它将仅"将它们中的每一个除以100.

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.

这篇关于用列表理解将列表的元素除以整数:索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆