# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)
# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]
# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
print i
# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
print i
# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
print i
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print i
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
x = ['apple', 'orange', 'grape', 'lion', 'banana', 'watermelon', 'onion', 'cat',]
for xr in x:
if xr in 'onion':
print('onion is a vegetable')
continue
if (xr not in 'lion' and xr not in 'cat'):
print(xr, 'is a fruit')
产出->
apple is a fruit
orange is a fruit
grape is a fruit
banana is a fruit
watermelon is a fruit
onion is a vegetable