[表达式 for 变量 in 旧列表]
[表达式 for 变量 in 旧列表 if 条件]
names = ['aaa', 'bbb', 'cccc', 'dd', 'eeeeee']
# 过滤掉 长度小于3的 字符串
n_names = [st.title() for st in names if len(st) > 3]
# n_names = [st.capitalize() for st in names if len(st) > 3]
print(names)
print(n_names)
n_list = [i for i in range(100) if i % 3 == 0 and i % 5 == 0]
print(n_list)
n_tl = [(x, y) for x in range(10) if x % 2 == 0 for y in range(1, 11) if y % 2 == 1]
print(n_tl)
sl = [100, 150, 130, 200, 220]
# 小于150的+50,大于150的+20
n_sl = [s + 50 if s < 150 else s + 20 for s in sl]
print(n_sl)
字典:
dict_1 = {'a': 'A', 'b': 'A', 'c': 'C', 'd': 'D', 'e': 'E'}
n_d1 = {a: b for b, a in dict_1.items()}
# 第二组 A:b 把 第一组 A:a 覆盖掉了
print(n_d1)