python exercises-3

(1) Delete the following names whose length is less than 2 characters, merge the names with different spellings but the same name, and output them in capitalized form.

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

(2) Count all the people with the same name in the list above and express them in the form of a dictionary. The required output format is as follows:

{‘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) Use two methods to remove duplicate elements from the list below

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) For the following two lists, if the elements are different, encapsulate each pair into a tuple, and pack all such stepless packages into a list. The expected results are as follows

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) Remove all spaces in the string

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

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

(6)

Get the number of Chinese characters in a string

str01 = "This is a wonderful story origin: abcdefasfas,123123124,here,asfasf,123,start"

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

(7) How to verify that each character in a string appears in another string


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)   

Guess you like

Origin blog.csdn.net/weixin_68479946/article/details/128842317