list comprehension 和python 中替代switch-case的方法

>>> 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值