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' 方法用於透過在一個迭代中省略第一個值來合併列表以及相同列表。

  • 將元素附加到一個空列表。

  • 此列表顯示為控制檯上的輸出。

  • 此列表再次排序並顯示在控制檯上。

更新日期:2021 年 9 月 13 日

341 次瀏覽

職業開局

透過完成課程獲得認證

開始
廣告
© . All rights reserved.