>>> num = [x for x in range(100) if x%2 ==0]
num
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = [fish for fish in fish_tuple if fish != 'octopus']
print(fish_list)
[‘blowfish’, ‘clownfish’, ‘catfish’]
Nested Loops in a List Comprehension
Nested loops can be used to perform multiple iterations in our programs.
Here is our nested for loop code block:
my_list = []
for x in [20, 40, 60]:
for y in [2, 4, 6]:
my_list.append(x * y)
print(my_list)
When we run this code, we receive the following output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
my_list = [x * y for x in [20, 40, 60] for y in [2, 4, 6]]
print(my_list)
my_list = [x * y for x in [1, 2, 3] for y in [100, 200, 300]]
my_list
[100, 200, 300, 200, 400, 600, 300, 600, 900]
line = '1234567890'
n = 2
[line[i:i+n] for i in range(0, len(line), n)]
[‘12’, ‘34’, ‘56’, ‘78’, ‘90’]
>>> list1 = (1,2,3,4)
>>> list2 = [(i, i*2) for i in list1] # Notice the braces around both items
print(list2)
[(1, 2), (2, 4), (3, 6), (4, 8)]
>>> list1 = [1, 2, 3]
>>> list2 = [(i, i*2, i) for i in list1]
list2
[(1, 2, 1), (2, 4, 2), (3, 6, 3)]
python 中替代switch-case的方法
choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
Short and simple for simple scenarios.
Compare to 11+ lines of C code:
// C Language version of a simple ‘switch/case’.
switch( key )
{
case 'a' :
result = 1;
break;
case 'b' :
result = 2;
break;
default :
result = -1;
}
You can even assign multiple variables by using tuples:
choices = {‘a’: (1, 2, 3), ‘b’: (4, 5, 6)}
(result1, result2, result3) = choices.get(key, (‘default1’, ‘default2’, ‘default3’))
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 is default if x not found
result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)