簡體   English   中英

從二維列表中提取項目

[英]Extracting items from 2d List

我有一個 2d 列表 splited_body:

splited_body= [
 ['startmsg', 'This is a test massage.', 'endmsg\r\n'], 
 ['startmsg', 'Hi There is some issue in the process.', '5', 'F3', 'D1', '2', 'endmsg\r\n']
]

我想在“endmsg”之前打印所有數據,並且我正在使用 for 和 if 組合,如下所示:

for i in range(len(splited_body)):
    for j in range(len(splited_body[i])):
        if splited_body[i][j] == 'endmsg':
            break
        x = splited_body[i][j]
        print(x)

但它正在打印列表中的所有項目。 我怎樣才能做到這一點。 請有人告訴我做錯了什么?

使用in關鍵字,您可以迭代列表中的各個元素。 所以你可以試試這個:

for body in splited_body:
    for msg in body:
        if msg.strip() == 'endmsg':
            break
        print(msg)

我會使用startswith

for b in splited_body:
    for i in b:
        if i.startswith('endmsg\r\n'):
            break
        print(i)

Python 通過 [:-1] 從列表中刪除最后一個元素。

for items in splited_body:
    print(items[:-1])

暫無
暫無

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

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