【python】列表推导式
程序员文章站
2024-01-06 14:10:58
...
#用简介的方式去遍历可迭代对象生成需要格式的列表
int_list = [1,2,3,4,5]
qu_list = [item * item for item in int_list]
print (type(qu_list))
int_list = [1,2,-3,4,5]
qu_list = [item if item > 0 else abs(item) for item in int_list]
#笛卡尔积
int_list1 = [1,2]
int_list2 = [3,4]
qu_list = [(first, second) for first in int_list1 for second in int_list2]
#1-100中3的倍数
p = [x for x in range(1,101) if x%3 == 0]
#1-100中,不是3的倍数的数去相反数,其余的数保持不变
q = [x if x%3==0 else -x for x in range(1,101)]
my_dict = {
"key1":"bobby1",
"key2":"bobby2"
}
# qu_list = [(key, value) for key, value in my_dict.items()]
#
# qu_list2 = list(((key, value) for key, value in my_dict.items()))
#
# for item in qu_list2:
# print (item)
int_list = [1,2,3,4,5]
def process_item(item):
return str(item)
int_dict = {process_item(item):item for item in int_list}
#列表生成式,第一:能用尽量用, 因为效率高
print (int_dict)
#set dict都可以推导
(for _ in range(2)) #这个是生成一个生成器