python列表推导式

a = [1, 2, 3, 4, 5, 6, 7]
# 将每个元素求平方 加入到b列表中
# 1.列表解析
b = [x ** 2 for x in a]
print(b)
# 2.用map实现
c = map(lambda x: x ** 2, a)
print(list(c))
# 3.用循环实现
d = []
for x in a:
    d.append(x ** 2)
print(d)

# 将a中的偶数求立方加入到新的列表中  奇数忽略
# 1.列表解析
e = [m ** 3 for m in a if m % 2 == 0]
print(e)

# 2.map +filter
f = map(lambda v: v ** 3, filter(lambda x: x % 2 == 0, a))
print(list(f))

# 3.循环
g = []
for p in a:
    if p % 2 == 0:
        g.append(p ** 3)
print(g)

"""
以上操作对set集合  元组也有效
"""

dict_a = {
    "黑旋风": "李逵",
    "及时雨": "宋江",
    "浪子": "燕青"
}
print(dict_a)
list_a =[key for key,value in dict_a.items()]
print(list_a)
# key value交换
dict_b ={value:key for key,value in dict_a.items()}
print(dict_b)

-------------------------------
C:\Python\Python36\python.exe D:/IdeaProjects/python_basic/extend/learn_list.py
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
[8, 64, 216]
[8, 64, 216]
[8, 64, 216]
{'黑旋风': '李逵', '及时雨': '宋江', '浪子': '燕青'}
['黑旋风', '及时雨', '浪子']
{'李逵': '黑旋风', '宋江': '及时雨', '燕青': '浪子'}

Process finished with exit code 0

你可能感兴趣的:(python基础)