首页 > 代码库 > python 使用循环生成list

python 使用循环生成list

#-*- coding:UTF-8 -*-

squares=[]
for  x  in range(10):
    squares.append(x**2)
     
print  squares
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#等价于
squares=[x**2 for  x  in range(10)]
print  squares
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


combs=[]
for  x  in  [1,2,3]:
     for  y  in [3,1,4]:
          if x!=y:
            combs.append((x,y))
print  combs
#等价于:
combs=[(x,y) for  x in [1,2,3] for  y  in [3,1,4] if x!=y]
print combs
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

vec=[-4,-2,0,2,4]
print [x*2 for  x in vec]
#[-8, -4, 0, 4, 8]

print 30*‘*‘,‘print  [x for  x  in vec if  x>=0]‘,30*‘*‘
print  [x for  x  in vec if  x>=0]
#[0, 2, 4]

print [abs(x) for x  in vec]
#[4, 2, 0, 2, 4]

freshfruit=[‘  banana‘,‘ apple  ‘,‘loganberry ‘,‘passion  fruit ‘]
#strip() 去除字符串首尾空格
print [weapon.strip() for weapon  in  freshfruit]
#[‘banana‘, ‘apple‘, ‘loganberry‘, ‘passion  fruit‘]

print  30*‘*‘,"[(x,x**2) for  x  in  range(6)]",30*‘*‘
print [(x,x**2) for  x  in  range(6)]
#[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

vec=[[1,2,3],[4,5,6],[7,8,9]]
print [num for elem  in vec  for  num  in  elem]
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

matrix=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
#list中的每个元素都是list,将list中的每个list元素中的元素按照索引组合成一个新的list
print [[row[i] for  row in matrix] for  i in range(4)]
#[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

transposed=[]
for  i in range(4):
    transposed.append([row[i] for  row  in  matrix])

print   transposed
#[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

#等价于:
transposed=[]
for  i  in range(4):
    transposed_row=[]
    for  row  in  matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)
print   transposed

#等价于zip(*matrix)
print  zip(*matrix)
#[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]    
 
 

 此外,map()也可以返回list,map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
#lambda表示匿名函数,冒号前面的x表示函数参数,冒号后面是表达式,匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果

squares=map(lambda x:x**2,range(10))
print   squares

#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

 

python 使用循环生成list