def common_items(L1, L2):
l=[]
#找出重复的
for x in L1:
if x in L2 and x not in l:
l.append(x)
#排序
list.sort(l)
return l
a=[1,90,3,21,34,31,3,9,11,23,9]
b=[3,31,90,6,11]
print(common_items(a, b))
a=['good','good','Level','are']
b=['We','are','good','Do','the','job','See','you','are']
print(common_items(a, b))
[3, 11, 31, 90]
[‘are’, ‘good’]
def find_palindromes(L):
l=[]
for x in L:
a=len(x)
for i in range(0,a):
if x[i]!=x[-(i+1)]:
break
if i==a-1:
l.append(x)
return l
list2=['excellent','are','anna','good','level','91019','reviver','10051','91819', 'madam']
print(find_palindromes(list2))
[‘anna’, ‘level’, ‘91019’, ‘reviver’, ‘91819’, ‘madam’]
import math
def slice_by_step(L, N):
n=math.ceil(len(L)/N)#列数
#list1=[['']*n for i in range(N)]#N*n的0二维列表(这里区分浅copy和深copy)
list2=[];
for i in range(0,N):
list1=[]
for j in range(0,n):
if i+j*N<len(L):
list1.append(L[i+j*N])
list2.append(list1)
return list2
C=[1,2,3,4,5,6,7,8,9,10,11,12]
print(slice_by_step(C,3))
C=['excellent','are','anna','good','level','91019','reviver','10051','madam']
print(slice_by_step(C,4))
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
[[‘excellent’, ‘level’, ‘madam’], [‘are’, ‘91019’], [‘anna’, ‘reviver’], [‘good’, ‘10051’]]
def remove_zeros(C):
l=C.split(",")
y=[]
for x in l:
for a in range(0,len(x)):
if x[a]!='0':#注意是字符‘0’
y.append(x[a:])
break
elif a==len(x)-1:#处理000的情况
y.append('0')
C=",".join(y)
return C
print(remove_zeros("089,0760,009"))
print(remove_zeros("00001,000,099"))
89,760,9
1,0,99
def mix_strings(a,b,n):
a1=list(a)#转成列表
b1=list(b)
for i in range(0,n):#交换
c=a1[i]
a1[i]=b1[i]
b1[i]=c
a1=''.join(a1)#转成字符串
b1=''.join(b1)
return(a1+" "+b1)
print(mix_strings('abc','xyz',2))
print(mix_strings('12345','56789',4))
xyc abz
56785 12349
#3,根据长度排序
countries=['New Zealand','Australia','China','United Kingdom','Togo','Turkey','Sao Tome and Principle','Samoa']
lenc=[]
for i in countries:
lenc.append((i,len(i)))#(名字,长度)放一起
lenc.sort(key=lambda x:x[1],reverse=True)#排序
#lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x[1]为函数体
list1=[]#放回列表
for i in lenc:
list1.append(i[0])#(名字,长度)放一起
print(list1)
[‘Sao Tome and Principle’, ‘United Kingdom’, ‘New Zealand’, ‘Australia’, ‘Turkey’, ‘China’, ‘Samoa’, ‘Togo’]
def string_even(S):
a=len(S)
b=[]
c=0
for x in range(0,a):
if x%2!=0:
b.append(S[x])
c+=ord(S[x])
b=''.join(b)
return(b+': '+str(c))
print(string_even("abcdef"))
print(string_even("python"))
bdf: 300
yhn: 335
'''排序'''
list=[64,25,12,22,11]#需要排序的序列
for i in range(1,len(list)):
key=list[i]#记录开始元素
j=i-1
'''如果第i个元素小于前面的元素,则该元素往前移'''
while j>=0 and key<list[j]:#如果key(第i个元素)小于前面元素
list[j+1]=list[j]#前面的元素往后移
j-=1
list[j+1]=key
print("Sort array:")
for i in range(len(list)):
print(list[i],end=' ')
解析:
第1次大循环:
至此,list=[25, 64, 12, 22, 11]
第2次大循环:
至此,list=[12, 25, 64, 22, 11]
第3次大循环:
至此,list=[12, 22, 25, 64, 11]
第4次大循环:
至此,list=[11, 12, 22, 25, 64]
把几行语句添加的txt文件里
i=0
lines=[]
while True:
line=input(">")
if line=='.':
print(i,"lines appended")
break
else:
with open('mytest2.txt','a') as f:
f.write(line+"\n")
i=i+1
with open(‘mytest2.txt’,‘a’) as f,一般可放在while前
import os
import sys
def pickAFile(thisDir = '.', extension = '*'):#若没有赋值则默认取.和*(thisDir为文件夹路径,extension为文件格式)
namesInThisDir = os.listdir(thisDir)#返回指定的文件夹包含的文件或文件夹的名字的列表
filelist = []
for item in namesInThisDir:
fullname = os.path.join(thisDir, item)
if os.path.isfile(fullname) and (item.endswith(extension) or extension == '*'):
#endswith用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False
#/是断句的意思,即这一行还没有结束
filelist.append(item)#把文件名加入列表
filelist.sort()#排序
choice = showMenu("Pick a file", filelist)#选择文件(根据序号)
if choice is not None:
return os.path.join(thisDir, filelist[choice])#返回选择的文件路径(组合文件路径时有\)
else:
return None
def showMenu(heading, itemlist):#显示文件列表
while True:
print ("\n *** " + heading + " ***\n")#输出第一行的那种格式
for i in range(len(itemlist)):
print ("%3d: %s" % (i, itemlist[i]))
print("\n Choice (or 'q')", end= " ")
reply = input(":")
if reply in ['q', 'Q']:
return None
else:
option = int(reply) # <<<<<<< ????
return option
while True:
choice = pickAFile('.', '*')
if choice:
print("You chose", choice)
else:
sys.exit(0)
with open("mytest.txt", 'r') as f:
lines=f.readlines() #读取内容到列表里
lines[2]="Sorry! The content of this line has been changed!\n"#把第3行内容改为Sorry!...
#第5行内容与第7行交换
templ=lines[4]
lines[4]=lines[6]
lines[6]=templ
#将"This line was inserted.\n"插入列表的第9行
lines.insert(8,"This line was inserted.\n")
numberofwords=0
for i in range(len(lines)):
words=lines[i].split()#分割单词(空格为分隔符)
tempcount=numberofwords+len(words)#求总单词长度
##这段意为从文本的第一行开始数,到第7个单词,去掉第七个单词。
if tempcount>=7:#如果总单词长度大于7
indexn=7-numberofwords-1#7-这一行之前的单词数目-1
del words[indexn]#删掉那个单词
lines[i]=" ".join(words)+"\n"#重新组合成句子
break#退出循环
else:
numberofwords=tempcount#没数到第7个继续数
#重新写入
with open("mytest.txt", 'w') as f:
f.writelines(lines)
#include
#include
//打印数字互不相同的三位数
int main()
{
int i,j,l;
printf("互不相同的三位数有");
for(i=1;i<=9;i++)
{
for(j=0;j<=9;j++)
{
for(l=0;l<=9;l++)
{
if(l!=i&&l!=j&&j!=i)
{printf(" ");
printf("%d%d%d",i,j,l);}
}
}
}
system("pause");
return 0;
}