Python – 根据前缀出现情况拆分字符串

pythonserver side programmingprogramming更新于 2025/10/23 1:16:17

当需要根据前缀的出现情况拆分字符串时,会定义两个空列表,并定义一个前缀值。使用简单迭代和‘append’方法。

示例

下面是相同的演示 −

from itertools import zip_longest

my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']

print("列表为: " )
print(my_list)

my_prefix = "python"
print("前缀为:")
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("结果是:")
print(my_result)

print("排序后的列表为: ")
my_result.sort()
print(my_result)

输出

列表为:
['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']
前缀为 :
python
结果为 :
[['hi', 'hello', 'there'], ['python', 'object', 'iented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]
排序后的列表为 :
[['hi', 'hello', 'there'], ['python', 'object', 'iented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]

解释

  • 将所需的包导入到环境中。

  • 定义字符串列表并显示在控制台上。

  • 定义前缀值并显示在控制台上。

  • 定义了两个空列表。

  • ‘zip_longest’方法用于通过省略迭代中的第一个值将列表与相同列表组合在一起。

  • 元素将附加到空列表之一。

  • 此列表显示为控制台上的输出。

  • 此列表再次排序并显示在控制台上。


相关文章


有用资源