[英]Unable to understand why this Python FOR loop isn't working as intended
I'm trying to generate a random dataset to plot a graph in Python 2.7. 我正在尝试生成随机数据集以在Python 2.7中绘制图形。
In which the 'y' list stores 14 integers between 100 and 135. I did that using the following code: 其中的“ y”列表存储100至135之间的14个整数。我使用以下代码进行了此操作:
y = [random.randint(100, 135) for i in xrange(14)]
And for the 'x' list, I wanted to store the index values of the elements in 'y'. 对于“ x”列表,我想将元素的索引值存储在“ y”中。 To achieve this, I tried using the code:
为此,我尝试使用以下代码:
x = []
for i in y:
pt = y.index(i)
x.append(pt)
But when I run this, the result of the for loop ends up being: 但是当我运行它时,for循环的结果最终是:
x = [0, 1, 1, 3, 4, 5, 6, 3, 1, 9, 1, 11, 12, 13]
Why isn't the result the following? 为什么没有以下结果?
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Python is returning the first location of a value in y. Python正在返回y中值的第一个位置。
Running your code, here's an example y
: 运行您的代码,这是一个示例
y
:
[127, 124, 105, 119, 121, 118, 130, 123, 122, 105, 110, 109, 108, 110]
110 is at both 10 and 13. 105 is at both 2 and 9. Python stops looking after it finds the first one, so x
then becomes: 110分别位于10和13。105分别位于2和9。Python停止寻找第一个,因此
x
然后变成:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 2, 10, 11, 12, 10]
list.index()
finds the index of the first occurrence of that object in the list
, which produces the results you saw when the list
has repeated elements. list.index()
查找该对象在list
首次出现的索引,该索引将产生您在list
包含重复元素时看到的结果。 Something like [1, 1, 1].index(1)
would produce 0
. 像
[1, 1, 1].index(1)
这样的东西会产生0
。
If you want to generate a list of indices, you can use list(range(len(y)))
, which finds the length of y
, creates a range()
object out of it, then creates a list
out of that object. 如果要生成索引列表,可以使用
list(range(len(y)))
,它找到y
的长度,从中创建一个range()
对象,然后从该对象中创建一个list
。 Since you're using Python 2, you can omit the list()
call, since Python 2's range()
will already return a list
. 由于您使用的是Python 2,因此可以省略
list()
调用,因为Python 2的range()
已经返回了list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.