python例子,,list1 = [[


技术图片

技术图片
list1 = [[‘张三‘,‘男‘,‘未婚‘,20],[‘李四‘,‘男‘,‘已婚‘,28],[‘小红‘,‘女‘,‘未婚‘,18],[‘小芳‘,‘女‘,‘已婚‘,25]]output = open(‘data.xls‘,‘w‘,encoding=‘gbk‘)output.write(‘name\tgender\tstatus\tage\n‘)for i in range(len(list1)):    for j in range(len(list1[i])):        output.write(str(list1[i][j]))    #write函数不能写int类型的参数,所以使用str()转化        output.write(‘\t‘)   #相当于Tab一下,换一个单元格    output.write(‘\n‘)       #写完一行立马换行output.close()
View Code

技术图片

技术图片
list1 = [[‘张三‘,‘男‘,‘未婚‘,20],[‘李四‘,‘男‘,‘已婚‘,28],[‘小红‘,‘女‘,‘未婚‘,18],[‘小芳‘,‘女‘,‘已婚‘,25]]output = open(‘data.txt‘,‘w‘,encoding=‘gbk‘)output.write(‘name,gender,status,age\n‘)for row in list1:    rowtxt = ‘{},{},{},{}‘.format(row[0],row[1],row[2],row[3])    output.write(rowtxt)    output.write(‘\n‘)output.close()
View Code

组合

combinations:不考虑顺序的排列组合import itertoolsprint list(itertools.combinations([1,2,3,4],3))[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]permutations:考虑顺序的排列组合import itertoolsprint list(itertools.permutations([1,2,3,4],2))  #第二个参数2表示要选几个对象[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

from itertools import productl = [1, 2, 3]print (list(product(l, l)))print (list(product(l, repeat=3)))结果:[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)][(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

python例子

评论关闭