时间:2021-07-01 10:21:17 帮助过:61人阅读
比如,一个list变量的元素均为数字,如果需要将每个元素的值乘以2并生成另外一个list,下面是一种做法:
list1 = [1,2,4,5,12]
list2 = []
for item in list1:
list2.append(item*2)
print list2
list1 = [1,2,4,5,12]
list2 = [item*2 for item in list1 ]
print list2
list1 = [1,2,4,5,12]
list2 = [item for item in list1 if item < 10 ]
print list2
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [(item1,item2) for item1 in list1 for item2 in list2 ]
print list3
matrix1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
matrix2 = [[row[i] for row in matrix1] for i in range(4)]
for row in matrix2:
print row