简体   繁体   中英

Python for-loop to list comprehension

I'm a beginner to Python and am teaching myself list comprehensions. 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.

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'".

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. I'm trying to check each of the n randoms for that condition. 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.

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. 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.

We use 1000.0 or float(len(y)) to avoid using integer division, which would result in 0 as the answer. Alternatively, you can use from __future__ import division to make the / division operator use float division by default, see PEP 238 .

Note that I made it a generator expression for you, no need to store a list first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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