简体   繁体   English

Python for循环列出理解

[英]Python for-loop to list comprehension

I'm a beginner to Python and am teaching myself list comprehensions. 我是Python的初学者,正在教自己列表理解。 I've been doing well with almost all of the for-loop code I've been translating to list comprehension, but am very stuck on what I thought was a fairly simple loop. 几乎所有我已经转换为列表理解的for循环代码我都做得很好,但我非常坚持我认为是一个相当简单的循环。

n = 10000

def sim(y):
  count = 0
  for i in range(10000):
    if 0.9 <= y[i] <= 1.8:
        count += 1
  probability = count/10000.0
  print("P(a < x <= b) : {0:8.4f}".format(probability))


print ("\t case: \n"),sim([0.25 if random() < 0.8 else 1.5 for r in range(n)])

So far I've been trying variations on the following but it's all getting errors related to the use of lists such as "'int' object is unsubscriptable" and "unsupported operand type(s) for +: 'int' and 'list'". 到目前为止,我一直在尝试对以下内容进行修改,但是所有错误都与使用列表相关,例如“'int'对象是unsubscriptable”和“不支持的操作数类型+”:'int'和'list' ”。

def sim(y):
  c4 = sum([y for range(y) in range(len(y)) if 0.9 < y[i] <= 1.8])/10000
  print("P(a < x <= b) : {0:8.4f}".format(c4))

The purpose is to basically take the parameter passed to sim() and iterate over the length of it while incrementing by 1 for only those values found true by the condition between 0.9 and 1.8. 目的是基本上将传递给sim()的参数传递给它并在其长度上迭代,同时仅增加1,因为只有那些在0.9和1.8之间的条件下找到的值为true。 I'm trying to check each of the n randoms for that condition. 我正试图检查那个条件中的每个n个randoms。 Then sum only those that are true. 然后总结那些真实的。

By the way, the answer should work out around 0.2 -- if you want to check it just think about 1.5 being the only way to fit between 0.9 and 1.8. 顺便说一下,答案应该在0.2左右 - 如果你想检查一下,只考虑1.5是唯一适合0.9和1.8之间的方法。

I appreciate your patience as I'm learning. 我正在学习,感谢你的耐心等待。

You still need to provide an expression for each loop, and your for y in section is rather out of hand. 你仍然需要为每个循环提供一个表达式,而你for y in section则相当失控。 The following works: 以下作品:

c4 = sum(1 for i in y if 0.9 < i <= 1.8) / 10000.0

This is the equivalent of: 这相当于:

count = 0
for i in y:
    if 0.9 < i <= 1.8:
        count += 1
c4 = count / 10000.0

Perhaps the 10000.0 should be float(len(y)) , but that's not entirely clear from your example. 也许10000.0应该是float(len(y)) ,但是你的例子并不完全清楚。

We use 1000.0 or float(len(y)) to avoid using integer division, which would result in 0 as the answer. 我们使用1000.0float(len(y))来避免使用整数除法,这将导致0作为答案。 Alternatively, you can use from __future__ import division to make the / division operator use float division by default, see PEP 238 . 或者,您可以使用from __future__ import division来使/ division运算符默认使用float division,请参阅PEP 238

Note that I made it a generator expression for you, no need to store a list first. 请注意,我为您创建了一个生成器表达式,无需先存储列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM