slacr_

Just to record my life and thoughts.
笔记/编程/杂乱/极简

[Python]字典推导

Nov 17, 2023Python161 words in 1 min

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{key_expression: value_expression for item in iterable if if_expression}

# 对于条件下的键和值
custom_dict = {x:y for x in range(10) for y in range(10) if x+y == 10}
print(custom_dict)


# 对于条件下不同函数的值
custom_dict = {num: (num**2 if num % 2 == 0 else num**3) for num in range(10)}
print(custom_dict)

# 对于条件下不同函数的键
custom_dict = {(num**2 if num % 2 == 0 else num**3 if num % 3 == 0 else num**4 if num%4 == 0 else num):num for num in range(10)}
print(custom_dict)

# 总结: 第一个表达式含义一定是循环最内层的键值对
custom_dic = { num:num**2 if num == 2 else num:num for num in range(5)}
  • Author:

    slacr_

  • Copyright:

  • Published:

    November 17, 2023

  • Updated:

    November 17, 2023

Buy me a cup of coffee ☕.

1000000