list comprehension

list can not use as follow:
list comprehension_第1张图片
the solution is list comprehension;
or use numpy.ndarray

x=[1,2,3,4]

#Q1: Compare x>1 element-by-element
print([s>1 for s in x])

#list comprehension
print(any([s>1 for s in x]))
# for loop
for s in x:
    if s>1:
        r=True
        break
else:
    r=False

#Q3: Are all elements of x greater than 1?
print(all([s>1 for s in x]))

#Q4: Compute x+1 element-by-element
print([s+1 for s in x])

#Q5: Compute x**2 element-by-element
print([s**2 for s in x])
#Q6: Test x in range(5) element-by-element
print ([s in range(5)])

#Q7: Is there any element of x in range(5)
print([any(s for s in range(5))])

#Q8: Are all elements of x in range(5)
print([all(s for s in range(5))])

你可能感兴趣的:(python)