簡體   English   中英

不管行數是多少,都從最后3行提取數據

[英]Extracting Data from the last 3 lines regardless of the number of lines

最近,我一直在使用某些Python影像庫,並且在從字符串的后三行提取文本時遇到了問題。

可以說我有一個字符串

a = '''
Human
Dog
Cat
Banana
Apple
Orange'''

我想將這些內容轉換為2個不同的列表,其中一個具有字符串的最后三行,另一個具有字符串的所有其余行。

first_items = ['Human', 'Dog', 'Cat']
last_items = ['Banana', 'Apple', 'Orange']

如何在Python中執行此操作?

首先,您需要按行排列數據,以過濾出空行:

lines = list(filter(None, a.splitlines()))

然后,您可以使用Python的列表切片

first = lines[:-3]
last = lines[-3:]
a = '''Human
Dog
Cat
Banana
Apple
Orange'''

full_list = a.split('\n')

list1 = full_list[:-3]
last_items = full_list[-3:]

輸出:

In [6]: list1
Out[6]: ['Human', 'Dog', 'Cat']

In [7]: last_items
Out[7]: ['Banana', 'Apple', 'Orange']

您可以對初始strip使用split以便刪除第一個\\n 然后使用其尺寸對列表進行切片,以使其可擴展到其他情況:

l = a.strip().split('\n')
l1, l2 = l[:len(l)//2], l[len(l)//2:] 

print(l1)
['Human', 'Dog', 'Cat']

print(l2)
['Banana', 'Apple', 'Orange']
a = '''
Human
Dog
Cat
Banana
Apple
Orange'''

a在這里是一個字符串,所以我們應該把它轉換成一個列表用換行字符分割它\\n ,並修剪領先\\n通過采取從第一個項目列表,而不是第0項

full_list = a.split('\n')[1:]

它會給出['Human', 'Dog', 'Cat', 'Banana', 'Apple', 'Orange']

現在可以使用[:-3]提取前三名,使用[-3:]提取后三名

list1 = full_list[:3]  
last_items = full_list[-3:]

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM