Python调用列表中的元素会返回错误的元素

2024-04-25 12:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

从这个列表中,我洗牌:

RotationSpeedArray = [4,6,8,10] #in Hz
random.shuffle(RotationSpeedArray)

我试着一次用一个特定的号码打电话

print RotationSpeedArray[0]
print RotationSpeedArray[1]
print RotationSpeedArray[2]
print RotationSpeedArray[3]

但每当我得到这个:

#an actual empty space
[
6
,

这部分的代码是用来画一个图形并旋转它的。我们想用不同的速度,所以这就是为什么我们创建了一个列表,从中获取一个旋转速度并使用它。这个数字实际上是以不同的速度移动的,所以一次取一个值的过程是有效的。我只是不明白为什么每当我要求显示列表中的每个值时,它都会这样做

我希望这是足够清楚的;请不要犹豫问我任何问题


Tags: 代码inan图形列表spacerandom速度
1条回答
网友
1楼 · 发布于 2024-04-25 12:24:46

我没有问题。你确定你没有把你的列表转换成一个字符串吗??它把旋转视为一根弦,这就是为什么我要问

如果您在列表中加了引号,random.shuffle将抛出一个TypeError,所以我假设您没有向我们显示的代码超出了将其转换为字符串的代码

import random
RotationSpeedArray = [4,6,8,10] #in Hz
random.shuffle(RotationSpeedArray)

# the problem is happening here


print(RotationSpeedArray[0])
print(RotationSpeedArray[1])
print(RotationSpeedArray[2])
print(RotationSpeedArray[3])

print(RotationSpeedArray)

# To demonstrate your particular issue, if we convert the list to a string
# we get the same problem you're having
StringArray = str(RotationSpeedArray)

print(StringArray[0])
print(StringArray[1])
print(StringArray[2])
print(StringArray[3])

print(StringArray)

输出:

10
6
4
8
[10, 6, 4, 8]
[
1
0
,
[10, 6, 4, 8]

相关问题 更多 >