【问题标题】:Why are the values being added on to my list twice each time? Issue in python为什么每次将值添加到我的列表中两次? python中的问题
【发布时间】:2014-04-27 05:34:54
【问题描述】:

我无法获取我正在尝试编写的正面和反面代码的列表。

import random

list4heads=[]
maximums=[]
base=10

list4tails=[]
percent4heads=[]
percent4tails=[]
for exponent in range (1,6):


    ranges=base**exponent
    results=[0,0]

    maximums.append(ranges)
    for num in range (1,ranges+1):   

        flip=random.randint(0,num)
        if flip%2==0:
            results[0]+=1


        elif flip%2 != 0:
            results[1]+=1


    for slot in results:


        list4heads.append(results[0])
        list4tails.append(results[1])


        hp= results[0]/(results[0]+results[1])
        tp= results[1]/(results[0]+results[1])
        percent4heads.append(hp)
        percent4tails.append(tp)



print(list4heads, '\n', list4tails)
print()
print()
print(percent4heads, '\n', percent4tails)

我需要将每个值添加一次,但我的输出看起来像这样。

[6, 6, 54, 54, 502, 502, 5053, 5053, 49746, 49746] 
 [4, 4, 46, 46, 498, 498, 4947, 4947, 50254, 50254]


[0.6, 0.6, 0.54, 0.54, 0.502, 0.502, 0.5053, 0.5053, 0.49746, 0.49746] 
 [0.4, 0.4, 0.46, 0.46, 0.498, 0.498, 0.4947, 0.4947, 0.50254, 0.50254]

为什么每个值要加两次? 提前致谢!

【问题讨论】:

  • 输出的前两行是“硬币翻转”落在正面然后是反面的时间。首先是 10 次投掷,然后是 100、1,000、10,000 和 100,000。接下来的 2 是每个结果的百分比。

标签: python list output


【解决方案1】:

您的列表results 有两个元素。您对其进行迭代,但在 每个 迭代中,您更新 both 头数和尾数,因此它们被更新两次(每次迭代一次)。删除您的 for slot in results 并取消缩进其中的代码,使其仅运行一次。

【讨论】:

  • 谢谢!感谢所有回答的人。
【解决方案2】:

你会的

for slot in results:

结果有 2 个元素。

这意味着这两行被调用了两次:

list4heads.append(results[0])
list4tails.append(results[1])

【讨论】:

    【解决方案3】:

    删除这一行:

    for slot in results:
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2023-04-03
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多