Python - 按前缀出现情况拆分字符串
当要求按前缀出现的情况拆分字符串时,定义两个空列表,并定义一个前缀值。一个简单的迭代与“append”方法同时使用。
示例
下面是同一示例的演示 −
from itertools import zip_longest
my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']
print("The list is : " )
print(my_list)
my_prefix = "python"
print("The prefix is :")
print(my_prefix)
my_result, my_temp_val = [], []
for x, y in zip_longest(my_list, my_list[1:]):
my_temp_val.append(x)
if y and y.startswith(my_prefix):
my_result.append(my_temp_val)
my_temp_val = []
my_result.append(my_temp_val)
print("The resultant is : " )
print(my_result)
print("The list after sorting is : ")
my_result.sort()
print(my_result)输出
The list is : ['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne'] The prefix is : python The resultant is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']] The list after sorting is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]
说明
将所需的程序包导入到环境中。
定义了一个字符串列表,并显示在控制台上。
定义前缀值并显示在控制台上。
定义两个空列表。
'zip_longest' 方法用于通过在一个迭代中省略第一个值来合并列表以及相同列表。
将元素附加到一个空列表。
此列表显示为控制台上的输出。
此列表再次排序并显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP