python习题-3

(1)将下列姓名长度小于2字符的删除,将写法不同但名字一样的名字合并,并按首字母大写形式输出。

names=['Bob','JOHN','alice','bob','ALICE','J','Bob']
name_replace={name.title() for name in names if len(name)>2}
print(name_replace)

(2)将上题列表中所有重名人员进行计数并以字典的形式表示出来 。要求输出 格式如下 :

{‘Bob’: 3, ‘John’: 1, ‘Alice’: 2}

names =['Bob','JOHN','alice','bob','ALICE','J','Bob']
name_replace =[name.title() for name in names if len(name)>2]
real_name={name:name_replace.count(name) for name in name_replace}
print(real_name)

(3)用两种方法将下面列表中的元素去重

a_list=[1,1,2,3,4,5,6,7,6,5,4,3,3,5,2]

# 方法一
a_list=[1,1,2,3,4,5,6,7,6,5,4,3,3,5,2]
a_dic={key:0 for key in a_list}
new_dict=a_dic.keys()
print(new_dict)
 
# 方法二
a_list=[1,1,2,3,4,5,6,7,6,5,4,3,3,5,2]
new_dict=list(set(a_list))
print(new_dict)

(4)对下面两个列表,如果元素不同则两两封装成一个元组,并将所有这样的无级打包成一个列表,预期的结果如下

list_a=[1,2,3]

list_b=[2,7]

[(1, 2), (1, 7), (2, 7), (3, 2), (3, 7)]

list_a=[1,2,3]
list_b=[2,7]
new_list=[(x,y) for x in list_a for y in list_b if x!=y]
print(new_list)

(5)去掉字符串中所有的空格

s = " sfafas asfasf afasf saf asfasf a asf asa"

s = " sfafas asfasf afasf saf asfasf a asf asa"
s1=s.replace(" ","")
print(s1)

(6)

获取字符串中汉字的个数

str01 = "这是一个美好的故事起源:abcdefasfas,123123124,在这里的,asfasf,123,开始"

str01 = "这是一个美好的故事起源:abcdefasfas,123123124,在这里的,asfasf,123,开始"
count = 0
for i in str01:
    if 0x4E00 <= ord(i) <= 0x9FA5:
        count += 1
 
print(f"字符串中的中文有{count}个")

(7)如何验证一个字符串中的每一个字符均在另一个字符串中出现


def is_in(full_str, sub_str):
    try:
        full_str.index(sub_str)
        return True
    except ValueError:
        return False
 
print(is_in("hello, python", "llo"))  
print(is_in("hello, python", "lol"))  
 
# 使用 in 和 not in
print("llo" in "hello, python") 
print("lol" in "hello, python")
 
# 使用 find
print("hello, python".find("llo") != -1)   
print("hello, python".find("lol") != -1)   

猜你喜欢

转载自blog.csdn.net/weixin_68479946/article/details/128842317
今日推荐