【问题标题】:Printed items from LISt do not match what was inserted来自 LISt 的打印项目与插入的项目不匹配
【发布时间】:2016-09-22 02:47:38
【问题描述】:

抱歉各位,对 Python 有点陌生,请多多包涵。

我正在尝试,只是为了让 S 和 G's 创建一个小型 Python 程序,该程序将采用 X 位数的 Pi,并将它们播放为 winsound.beeps(不要问)。

我得到了哔哔声,并且我将 Pi 插入了一个列表。当我打印列表时,它不正确。谁能指出我做错了什么?

#!/usr/bin/python
from mpmath import *

import winsound

mp.dps = 10

floatPi = mp.pi
print(floatPi)

conPi = str(floatPi)
print(conPi)

strPi = conPi.replace(".", "")
print(strPi)

listPi = []

for digit in strPi:
    listPi.append(int(digit))

print listPi
#winsound.Beep(floatPi*100, 300)

for number in listPi:
    print(listPi[number])
    #winsound.Beep(listPi[number]*100, 300)

结果如下

3.141592654
3.141592654
3141592654
[3, 1, 4, 1, 5, 9, 2, 6, 5, 4]
1
1
5
1
9
4
4
2
9
5

为什么从 for 循环中打印出来的列表不是 Pi?

【问题讨论】:

  • for number in listPi: 你觉得有什么作用?

标签: python list python-2.7


【解决方案1】:

代码应该是,

for number in listPi:
    print(number)

因为在这里您正在遍历列表的内容而不是与它们关联的键,例如,以第一种情况为例,它是print(listPi[number]),它基本上打印lisPi[3],即1

如果你来自 c/c++/java ,

for i in range(0,len(listPi),1):
    print(listPi[i])

这会更熟悉。

【讨论】:

    【解决方案2】:

    使用以下作为最后一个 for 循环:

    for number in listPi:
        print(number)
    

    for 循环一一为您提供列表中的内容。您无需再次在列表中查找。

    【讨论】:

    • 乐于助人。如果它解决了问题,您可以接受答案。
    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多