Python - 等距连续字符字符串
给定一个字符串列表,提取所有字符串,其连续字符在 ASCII 顺序上有共同的差异。
Input : test_list = [“abcd”, “egil”, “mpsv”, “abd”]
Output : [‘abcd’, ‘mpsv’]
Explanation : In mpsv, consecutive characters are at distance 3.
Input : test_list = [“abcd”, “egil”, “mpsw”, “abd”]
Output : [‘abcd’]
Explanation : In abcd, consecutive characters are at distance 1.
方法 #1:使用列表理解+ all()
在这里,我们使用 all() 检查每个具有共同差异的字符,并使用列表理解来迭代字符串。
Python3
# Python3 code to demonstrate working of
# Equidistant consecutive characters Strings
# Using list comprehension + all()
# initializing list
test_list = ["abcd", "egil", "mpsv", "abd"]
# printing original list
print("The original list is : " + str(test_list))
# ord() used to get ASCII value
res = [sub for sub in test_list if all(ord(
sub[idx + 1]) - ord(sub[idx]) == ord(sub[1]) - ord(sub[0]) for idx in range(0, len(sub) - 1))]
# printing result
print("Filtered Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Equidistant consecutive characters Strings
# Using list comprehension + all()
# initializing list
test_list = ["abcd", "egil", "mpsv", "abd"]
# printing original list
print("The original list is : " + str(test_list))
# ord() used to get ASCII value
res = [sub for sub in test_list if all(ord(sub[idx + 1]) - ord(sub[idx]) == ord(sub[1]) - ord(sub[0]) for idx in range(0, len(sub) -1 ))]
# printing result
print("Filtered Strings : " + str(res))
输出
The original list is : ['abcd', 'egil', 'mpsv', 'abd']
Filtered Strings : ['abcd', 'mpsv']
方法 #2:使用filter() + lambda + ord() + all()
在这里,我们使用 filter() 和 lambda函数执行过滤任务。 ord() 的任务是获得每个字符的 ASCII 等价物。
蟒蛇3
# Python3 code to demonstrate working of
# Equidistant consecutive characters Strings
# Using list comprehension + all()
# initializing list
test_list = ["abcd", "egil", "mpsv", "abd"]
# printing original list
print("The original list is : " + str(test_list))
# ord() used to get ASCII value
res = [sub for sub in test_list if all(ord(sub[idx + 1]) - ord(sub[idx]) == ord(sub[1]) - ord(sub[0]) for idx in range(0, len(sub) -1 ))]
# printing result
print("Filtered Strings : " + str(res))
输出
The original list is : ['abcd', 'egil', 'mpsv', 'abd']
Filtered Strings : ['abcd', 'mpsv']