⑴ C语言求助:请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
用下面的代码给你提供个思路。这代码连续字符不得超过9个……
#include "stdio.h"
void main(void){
char a[1000]="gcccddecc";
int i,j,k,n;
printf("Type an integer(a~z)...\nStr=");
gets(a);
for(k=i=0;a[i];i++){
for(j=i+1,n=0;a[i]==a[j];j++) n++;
if(n){
a[k++]=n+'1';
a[k++]=a[--j];
i+=n;
}
else a[k++]=a[i];
}
a[k]='\0';
printf("The result = %s.\n",a);
}
⑵ 6 个值得玩味的 python 代码
先选取了 6 个自己认为值得玩味的 python代码,希望对正在学习 python 的你有所帮助。
1、类有两个方法,一个是 new,一个是 init,有什么区别,哪个会先执行呢?
运行结果如下:
再来看另一个例子
运行结果如下:
这里给出官方的解释: init 作用是类实例进行初始化,第一个参数为 self,代表对象本身,可以没有返回值。 new 则是返回一个新的类的实例,第一个参数是 cls 代表该类本身,必须有返回值。很明显,类先实例化才能产能对象,显然是 new 先执行,然后再 init ,实际上,只要 new 返回的是类本身的实例,它会自动调用 init 进行初始化。但是有例外,如果 new 返回的是其他类的实例,则它不会调用当前类的 init 。下面我们分别输出下对象 a 和对象 b 的类型:
可以看出,a 是 test 类的一个对象,而 b 就是 object 的对象。
2、map 函数返回的对象
map()函数第一个参数是 fun,第二个参数是一般是 list,第三个参数可以写 list,也可以不写,作用就是对列表中 list 的每个元素顺序调用函数 fun 。
有没有发现,第二次输出 b 中的元素时,发现变成空了。原因是 map() 函数返回的是一个迭代器,并用对返回结果使用了 yield,这样做的目的在于节省内存。 举个例子:
执行结果为:
这里如果不用 yield,那么在列表中的元素非常大时,将会全部装入内存,这是非常浪费内存的,同时也会降低效率。
3、正则表达式中 compile 是否多此一举?
比如现在有个需求,对于文本 中国 ,用正则匹配出标签里面的“中国”,其中 class 的类名是不确定的。有两种方法,代码如下:
这里为什么要用 compile 多写两行代码呢? 原因是 compile 将正则表达式编译成一个对象,加快速度,并重复使用。
4、[[1,2],[3,4],[5,6]]一行代码展开该列表,得出[1,2,3,4,5,6]
5、一行代码将字符串 "->" 插入到 "abcdefg"中每个字符的中间
这里也建议多使用 os.path.join() 来拼接操作系统的文件路径。
6、zip 函数
zip() 函数在运算时,会以一个或多个序列(可迭代对象)做为参数,返回一个元组的列表。同时将这些序列中并排的元素配对。zip() 参数可以接受任何类型的序列,同时也可以有两个以上的参数;当传入参数的长度不同时,zip 能自动以最短序列长度为准进行截取,获得元组。
//函数:文件压缩 //压缩参数:需要压缩的文件或文件夹(文件可为数组),压缩后的zip文件名及存放路径,压缩类型1:文件夹2:文件,后续操作1:压缩后下载;2:存放在服务器上(默认为/@Upload下) //压缩文件夹示例:Tozip("./","../".date("d-H-i-s").".zip",1,2); //压缩文件示例: // $aaa=array("../1.txt","../2.txt"); // Tozip($aaa,"../2.zip",2);FunctionTozip($Path, $ZipFile, $Typ=1, $Todo=1){//IF(!is_writeable($Path)){Exit("文件夹不可写!");}$Path=Str_iReplace("\\","/",($Path));IF(Is_Null($Path) OrEmpty($Path) Or!IsSet($Path)){ReturnFalse;}IF(Is_Null($ZipFile) OrEmpty($ZipFile) Or!IsSet($ZipFile)){ReturnFalse;} Include_once("inc/Class_Zip.php");$zip=NewPHPZip;IF(SubStr($Path,-1,1)=="/"){$Path=SubStr($Path,0, StrLen($Path)-1);} OB_end_clean();Switch($Typ){Case"1":$zip-ZipDir($Path, $ZipFile, $Todo);Break;Case"2":$zip-ZipFile($Path,
/**
*类名:zipFileRelease
*说明:一个zip文件解压类
*介绍:主要的zip文件释放方法releaseHandle()
* 用ZipInputStream类和ZipEntry类将zip文件的入口清单列举出来,然后
* 根据用户提供的输出路径和zip文件的入口进行组合通过DataOutputStream
* 和File类进行文件的创建和目录的创建,创建文件时的文件数据是通过
* ZipInputStream类、ZipEntry类、InputStream类之间的套嵌组合获得的。
*注意:如果zip文件中包含中文路径程序将会抛出异常
*日期:2005-7-1
*作者:Pcera
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
class zipFileRelease{
private String inFilePath;
private String releaseFilePath;
private String[] FileNameArray; //存放文件名称的数组
private ZipEntry entry;
//
private FileInputStream fileDataIn;
private FileOutputStream fileDataOut;
private ZipInputStream zipInFile;
private DataOutputStream writeData;
private DataInputStream readData;
//
private int zipFileCount = 0; //zip文件中的文件总数
private int zipPathCount = 0; //zip文件中的路径总数
/**
*初始化函数
*初始化zip文件流、输出文件流以及其他变量的初始化
*/
public zipFileRelease(String inpath,String releasepath){
inFilePath = inpath;
releaseFilePath = releasepath;
}
/**
*初始化读取文件流函数
*参数:FileInputStream类
*返回值:初始化成功返回0,否则返回-1
*/
protected long initInStream(ZipInputStream zipFileA){
try{
readData = new DataInputStream(zipFileA);
return 0;
}catch(Exception e){
e.printStackTrace();
return -1;
}
}
/**
*测试文件路径
*参数:zip文件的路径和要释放的位置
*返回值:是两位整数,两位数中的十位代表输入路径和输出路径(1输入、2输出)
* 各位数是代表绝对路径还是相对路径(1绝对、0相对)
* 返回-1表示路径无效
protected long checkPath(String inPath,String outPath){
File infile = new File(inPath);
File infile = new File(outPath);
}
*/
/**
*初始化输出文件流
*参数:File类
*返回值:初始化成功返回0,否则返回-1
*/
protected long initOutStream(String outFileA){
try{
fileDataOut = new FileOutputStream(outFileA);
writeData = new DataOutputStream(fileDataOut);
return 0;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*测试文件是否存在方法
*参数:File类
*返回值:如果文件存在返回文件大小,否则返回-1
*/
public long checkFile(File inFileA){
if (inFileA.exists()){
return 0;
}else{
return -1;
}
}
/**
*判断文件是否可以读取方法
*参数:File类
*返回值:如果可以读取返回0,否则返回-1
*/
public long checkOpen(File inFileA){
if(inFileA.canRead()){
return inFileA.length();
}else{
return -1;
}
}
/**
*获得zip文件中的文件夹和文件总数
*参数:File类
*返回值:如果正常获得则返回总数,否则返回-1
*/
public long getFilFoldCount(String infileA){
try{
int fileCount = 0;
zipInFile = new ZipInputStream(new FileInputStream(infileA));
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
zipPathCount++;
}else{
zipFileCount++;
}
fileCount++;
}
return fileCount;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*读取zip文件清单函数
*参数:File类
*返回值:文件清单数组
*/
public String[] getFileList(String infileA){
try{
ZipInputStream AzipInFile = new ZipInputStream(new FileInputStream(infileA));
//创建数组对象
FileNameArray = new String[(int)getFilFoldCount(infileA)];
//将文件名清单传入数组
int i = 0;
while ((entry = AzipInFile.getNextEntry()) != null){
FileNameArray[i++] = entry.getName();
}
return FileNameArray;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*创建文件函数
*参数:File类
*返回值:如果创建成功返回0,否则返回-1
*/
public long writeFile(String outFileA,byte[] dataByte){
try{
if (initOutStream(outFileA) == 0){
writeData.write(dataByte);
fileDataOut.close();
return 0;
}else{
fileDataOut.close();
return -1;
}
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*读取文件内容函数
*参数:File类
*返回值:如果读取成功则返回读取数据的字节数组,如果失败则返回空值
*/
protected byte[] readFile(ZipEntry entryA,ZipInputStream zipFileA){
try{
long entryFilelen;
if (initInStream(zipFileA) == 0){
if ((entryFilelen = entryA.getSize()) >= 0){
byte[] entryFileData = new byte[(int)entryFilelen];
readData.readFully(entryFileData,0,(int)entryFilelen);
return entryFileData;
}else{
return null;
}
}else{
return null;
}
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*创建目录函数
*参数:要创建目录的路径
*返回值:如果创建成功则返回0,否则返回-1
*/
public long createFolder(String dir){
File file = new File(dir);
if (file.mkdirs()) {
return 0;
}else{
return -1;
}
}
/**
*删除文件
*参数:要删除的文件
*返回值:如果删除成功则返回0,要删除的文件不存在返回-2
* 如果要删除的是个路径则返回-3,删除失败则返回-1
*/
public long deleteFile(String Apath) throws SecurityException {
File file = new File(Apath.trim());
//文件或路径不存在
if (!file.exists()){
return -2;
}
//要删除的是个路径
if (!file.isFile()){
return -3;
}
//删除
if (file.delete()){
return 0;
}else{
return -1;
}
}
/**
*删除目录
*参数:要删除的目录
*返回值:如果删除成功则返回0,删除失败则返回-1
*/
public long deleteFolder(String Apath){
File file = new File(Apath);
//删除
if (file.delete()){
return 0;
}else{
return -1;
}
}
/**
*判断所要解压的路径是否存在同名文件
*参数:解压路径
*返回值:如果存在同名文件返回-1,否则返回0
*/
public long checkPathExists(String AreleasePath){
File file = new File(AreleasePath);
if (!file.exists()){
return 0;
}else{
return -1;
}
}
/**
*删除zip中的文件
*参数:文件清单数组,释放路径
*返回值:如果删除成功返回0,否则返回-1
*/
protected long deleteReleaseZipFile(String[] listFilePath,String releasePath){
long arrayLen,flagReturn;
int k = 0;
String tempPath;
//存放zip文件清单的路径
String[] pathArray = new String[zipPathCount];
//删除文件
arrayLen = listFilePath.length;
for(int i=0;i<(int)arrayLen;i++){
tempPath = releasePath.replace('\\','/') + listFilePath[i];
flagReturn = deleteFile(tempPath);
if (flagReturn == -2){
//什么都不作
}else if (flagReturn == -3){
pathArray[k++] = tempPath;
}else if (flagReturn == -1){
return -1;
}
}
//删除路径
for(k = k - 1;k>=0;k--){
flagReturn = deleteFolder(pathArray[k]);
if (flagReturn == -1) return -1;
}
return 0;
}
/**
*获得zip文件的最上层的文件夹名称
*参数:zip文件路径
*返回值:文件夹名称,如果失败则返回null
*/
public String getZipRoot(String infileA){
String rootName;
try{
FileInputStream tempfile = new FileInputStream(infileA);
ZipInputStream AzipInFile = new ZipInputStream(tempfile);
ZipEntry Aentry;
Aentry = AzipInFile.getNextEntry();
rootName = Aentry.getName();
tempfile.close();
AzipInFile.close();
return rootName;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*释放流,释放占用资源
*/
protected void closeStream() throws Exception{
fileDataIn.close();
fileDataOut.close();
zipInFile.close();
writeData.flush();
}
/**
*解压函数
*对用户的zip文件路径和解压路径进行判断,是否存在和打开
*在输入解压路径时如果输入"/"则在和zip文件存放的统计目录下进行解压
*返回值:0表示释放成功
* -1 表示您所要解压的文件不存在、
* -2表示您所要解压的文件不能被打开、
* -3您所要释放的路径不存在、
* -4您所创建文件目录失败、
* -5写入文件失败、
* -6表示所要释放的文件已经存在、
* -50表示文件读取异常
*/
public long releaseHandle() throws Exception{
File inFile = new File(inFilePath);
File outFile = new File(releaseFilePath);
String tempFile;
String zipPath;
String zipRootPath;
String tempPathParent; //存放释放路径
byte[] zipEntryFileData;
//作有效性判断
if (checkFile(inFile) == -1) {
return -1;}
if (checkOpen(inFile) == -1) {
return -2;}
//不是解压再当前目录下时对路径作有效性检验
if (!releaseFilePath.equals("/")){
//解压在用户指定目录下
if (checkFile(outFile) == -1) {
return -3;}
}
//获得标准释放路径
if (!releaseFilePath.equals("/")) {
tempPathParent = releaseFilePath.replace('\\','/')+ "/";
}else{
tempPathParent = inFile.getParent().replace('\\','/')+ "/";
}
//获得zip文件中的入口清单
FileNameArray = getFileList(inFilePath);
//获得zip文件的最上层目录
zipRootPath = getZipRoot(inFilePath);
//
fileDataIn = new FileInputStream(inFilePath);
zipInFile = new ZipInputStream(fileDataIn);
//判断是否已经存在要释放的文件夹
if (zipRootPath.lastIndexOf("/") > 0 ){
if (checkPathExists(tempPathParent +
zipRootPath.substring(0,zipRootPath.lastIndexOf("/"))) == -1){
return -6;
}
}else{
if (checkPathExists(tempPathParent + zipRootPath) == -1){
return -6;
}
}
//
try{
//创建文件夹和文件
int i = 0;
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
//创建目录
zipPath = tempPathParent + FileNameArray[i];
zipPath = zipPath.substring(0,zipPath.lastIndexOf("/"));
if (createFolder(zipPath) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -4;
}
}else{
//读取文件数据
zipEntryFileData = readFile(entry,zipInFile);
//向文件写数据
tempFile = tempPathParent + FileNameArray[i];
//写入文件
if (writeFile(tempFile,zipEntryFileData) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -5;
}
}
i++;
}
//释放资源
closeStream();
return 0;
}catch(Exception e){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
e.printStackTrace();
return -50;
}
}
/**
*演示函数
*根据用户输入的路径对文件进行解压
*/
public static void main(String args[]) throws Exception {
long flag; //返回标志
String inPath,releasePath;
//获得用户输入信息
BufferedReader userInput = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("请输入zip文件路径:");
inPath = userInput.readLine();
System.out.println("请输入保存路径:");
releasePath = userInput.readLine();
userInput.close();
//执行解压缩
zipFileRelease pceraZip = new zipFileRelease(inPath,releasePath);
flag = pceraZip.releaseHandle();
//出错信息打印
if (flag == 0) System.out.println("释放成功!!!");
if (flag == -1) System.out.println("您所要解压的文件不存在!");
if (flag == -2) System.out.println("您所要解压的文件不能被打开!");
if (flag == -3) System.out.println("您所要释放的路径不存在!");
if (flag == -4) System.out.println("您所创建文件目录失败!");
if (flag == -5) System.out.println("写入文件失败!");
if (flag == -6) System.out.println("文件已经存在!");
if (flag == -50) System.out.println("文件读取异常!");
}
}
⑸ python中zip函数详解
a=[1,2,3,4,5,6,7,8,9]
b=[5,9,2,4,5,7,3,1,7]
c=list(zip(a,b))#打包
print(c)
输出内容:[[1,5],[2,9],[3,2],[4,4],[5,5],[6,7],[7,3],[8,1],[9,7]]
d=list(zip(*c))#解包
print(d)
输出内容:[[1,2,3,4,5,6,7,8,9],[5,9,2,4,5,7,3,1,7]]
⑹ python 当中的zip( )函数到底是干嘛的
这个可以理解为拉链,将两个list拉到一起来,每个对应元素做一定操作后,合并成一个list.
比如:
zip([1,2,3],['a','b','c'])
结果是
[(1, 'a'), (2, 'b'), (3, 'c')]
⑺ 请简述zip函数的功能及Python.3.x中使用zip函数生成列表的方法。
一、zip函数的功能如下:
将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。当各个迭代器中元素的个数不一致时,则返回列表中长度最短的情况,利用 *号操作符,可以将元组解压为列表。
二、Python.3.x中使用zip函数生成列表的方法如下:
1、作出说明,使用zip函数将可迭代的对象作为参数。
2、将对象中对应的元素打包成一个个元组。
3、用zip函数平行地遍历多个迭代器,如果可迭代对象的长度不相同将按短的序列为准。
4、遍历过程中产生元组,Python.3.x会把元组生成好,然后生成列表。
⑻ python zip函数的用法
定义:zip([iterable, ...])
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些 tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压),看下面的例子就明白了:
1 2 3 4 5 6 7 8 9
>>> a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) [(1, 2, 3), (4, 5, 6)]
对于这个并不是很常用函数,下面举几个例子说明它的用法:
* 二维矩阵变换(矩阵的行列互换)
比如我们有一个由列表描述的二维矩阵
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
通过python列表推导的方法,我们也能轻易完成这个任务
1 2
print [ [row[col] for row in a] for col in range(len(a[0]))] [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
另外一种让人困惑的方法就是利用zip函数:
1 2 3 4 5
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> zip(*a) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> map(list,zip(*a)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
这种方法速度更快但也更难以理解,将list看成tuple解压,恰好得到我们“行列互换”的效果,再通过对每个元素应用list()函数,将tuple转换为list
* 以指定概率获取元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
>>> import random >>> def random_pick(seq,probabilities): x = random.uniform(0, 1) cumulative_probability = 0.0 for item, item_probability in zip(seq, probabilities): cumulative_probability += item_probability if x < cumulative_probability: break return item >>> for i in range(15): random_pick("abc",[0.1,0.3,0.6]) 'c' 'b' 'c' 'c' 'a' 'b' 'c' 'c' 'c' 'a' 'b' 'b' 'c' 'a' 'c'
这个函数有个限制,指定概率的列表必须和元素一一对应,而且和为1,否则这个函数可能不能像预想的那样工作。
稍微解释下,先利用random.uniform()函数生成一个0-1之间的随机数并复制给x,利用zip()函数将元素和他对应的概率打包成tuple,然后将每个元素的概率进行叠加,直到和大于x终止循环
这样,”a”被选中的概率就是x取值位于0-0.1的概率,同理”b”为0.1-0.4,”c”为0.4-1.0,假设x是在0-1之间平均取值的,显然我们的目的已经达到
⑼ python中zip函数有哪些高级用法
zip() 功能是从参数的多个迭代器中选取元素组合成一个新的迭代器。顾名思义,它就是一个将对象进行打包和解包的函数。
它可以传入的参数包括;元组、列表、字典等迭代器
它返回一个zip对象,其内部元素为元组,一组一组的,可以转化为列表或元组,这里要强调一下,Python2和Python3中返回的zip对象有所不同。
Python3中zip()函数再不再返回list对象,但是可以通过list强行转换。(类似的函数变化还有dictionary关联的keys()、values()、items(),map(),filter())。
打包zip(iterables)
上面的代码使用的环境是Python3.6,其中list (z)操作就是强制转换。注意一个问题,a和b这两个列表是不同长短的,这时候zip函数就会匹配完最短的那个便结束。
当zip函数的参数只有一个时,它将从iterable中依次取一个元素,组成一个元组。
解包zip(*iterables)
解包,zip 相反,可理解为解压,返回多维矩阵形式,有几个组元素就返回几维的。
比如,下面我是用三个列表组合起来的迭代式,那么解压后就返回三维的矩阵
zip高级用法
讲完了基本的再来说一下该函数的高级用法。高级用法离不开一个词:Pythonic,就是将代码写的更优雅美观,看起来有逼格!
1. 列表推导
例如:
a = [1,2,3,4]
b = [5,6,7,8]
我们要同时遍历a、b,且要对它们进行操作,那就要放在同一个for循环内,zip函数正好合适
注意:如果是Python2环境中,要使用izip才能提高效率。
当然,如果你需要对下标进行操作,那么还需要加上enumerate函数
2. 使用zip创建键值对,zip方法返回的是一个元组,用它来创建键值对,简单明了。