[英]list comprehension with tuple comparision
輸入: [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
預期輸出: [("abc", 1, "def"), ("bc", 2, "a"), ("bc", 3, "a")]
我正在嘗試類似的東西: field_list = [field for i, field in enumerate(field_list) for cmp_field in field_list[i+1:] if]
......不知道if
適合這里?
我想使用列表理解來實現這一點。 獲取輸出的邏輯-刪除重復項(如果item [0]和item [1]相同,則將元組視為重復項)。
我可以使用傳統的for循環來實現它,但是我想通過列表理解來實現。 有什么想法嗎?
編輯:(“ abc”,1,“ def”)和(“ abc”,1,“ ghi”)是重復的,所以我可以選擇第一個。
output = [(x, y, z) for j, (x, y, z) in enumerate(input) if (x, y) not in [(x2, y2) for x2, y2, _ in input[:j]]]
# output = [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]
但是,使用傳統的for循環可能會更有效,因為您不需要在每次迭代(或Ashwini Chaudhary建議的集合)時構建第二個列表。
以從中得到啟發這個 ,你可以嘗試
inp = [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
res = []
[res.append(el) for el in inp if not [tmp for tmp in res if tmp[0] == el[0] and tmp[1] == el[1]]]
盡管我相信常規的for循環會更好地適合您的情況。
我使用了groupby,這是一個中間步驟。 。
In [40]: l=[("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
In [41]: from itertools import groupby
In [42]: groups=[list(g) for k,g in groupby(l,key=itemgetter(1))]
In [43]: groups
Out[43]:
[[('abc', 1, 'def'), ('abc', 1, 'ghi')],
[('bc', 2, 'a'), ('bc', 2, 'b')],
[('bc', 3, 'a')]]
In [44]: [elem[0] for elem in groups]
Out[44]: [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.