簡體   English   中英

從字符串列表列表中解析元素

[英]Parsing elements from list of list of strings

list = [[1,'abc'], [2, 'bcd'], [3, 'cde']]

我有一個如上所示的列表。

我想解析列表並嘗試獲取僅包含所有列表的第二個元素的列表。

output = ['abc','bcd','cde']

我想我可以通過查看整個列表並將第二個元素添加到新列表中來實現:

output = []
for i in list:
    output.append(i[1])

類似的東西,但請告訴我是否有更好的方法。

您可以使用列表理解:

l = [[1,'abc'], [2, 'bcd'], [3, 'cde']]
new_l = [b for _, b in l]

輸出:

['abc', 'bcd', 'cde']

另一種方法是使用來自operator模塊的itemgetter

from operator import itemgetter

l = [[1,'abc'], [2, 'bcd'], [3, 'cde']]

result = list(map(itemgetter(1), l))

print(result)

輸出:

['abc', 'bcd', 'cde']

另一個不那么優雅的方法是使用zip函數,從新創建的列表中取出第二個元素並將其轉換為list

result = list(list(zip(*l))[1])

暫無
暫無

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

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