[英]Python remove list with duplicated fields in a list of lists
當列表中的字段在 python3 中重復時,我希望能夠從列表列表中刪除一個元素。
IE:
當第二個字段重復時,從以下列表列表中刪除。 從
[["John","France"], ["Mike", "France"], ["Ana","Italy"]]
到
[["John","France"], ["Ana","Italy"]]
編輯:我已經嘗試了以下循環,但我期待着一種更有效的方法,如果它存在的話。
for element in consult_array:
for other_elements in consult_array:
if element[1] == other_elements[1]:
if element != other_elements:
consult_array.pop(element)
data = [["John", "France"], ["Mike", "France"], ["Ana", "Italy"]]
output = []
already_seen_countries = set()
for item in data:
country = item[1]
if country not in already_seen_countries:
output.append(item)
already_seen_countries.add(country)
print(output) # [['John', 'France'], ['Ana', 'Italy']]
如果您喜歡單行解決方案:
l = [["John","France"], ["Mike", "France"], ["Ana","Italy"]]
list(t for t in {e[1]: e for e in l[::-1]}.values())[::-1]
輸出:
[['John', 'France'], ['Ana', 'Italy']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.