第一题,统计字符串单词个数
def main():#def:定义函数
s = input("请输入字符串:")
ls = s.split(" ")#split()返回一个字符串数组,分解位置为" "
print("其中单词的总数为:",len(ls))
if __name__ == '__main__':
main()
1.split()函数解析
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
输出结果如下:
[‘Line1-abcdef’, ‘Line2-abc’, ‘Line4-abcd’]
[‘Line1-abcdef’, ‘\nLine2-abc \nLine4-abcd’]
第二题,删除list中的重复元素
def qccfx(K):
K1 = []
for i in K:
if i not in K1:
K1.append(i)#append() 方法用于在列表末尾添加新的对象。
return K1
print(qccfx([1,0,0,8,6,1,1]))
第三题,求列表中的元素个数,最大值,最小值,平均数,和元素之和
def choose(s):
sum = 0
all = 0
maxnum = max(s)#max() 方法返回给定参数的最大值,参数可以为序列。
minnum = min(s)
for i in s:
sum = sum + 1 #元素个数
all = all + i
average = all / sum
print(str("元素个数{0},最大值{1},最小值{2},元素和{3},平均值{4}").format(sum, maxnum, minnum, all, average))
def main():
s = [9,7,8,3,2,1,55,6]
choose(s)
main()
第四题,列表中的偶数平方,基数不变
def word_len(s):
# s = [i ** 2 for i in s if i % 2 == 0]
L = []
for i in s:
if(i % 2 == 0):
L.append(i** 2)
else:
L.append(i)
return L
def main():
s = [9,7,8,3,2,1,5,6]
print("变换前,s=",s)
print("变换后,s=",word_len(s))
main()