Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

Remove duplicate element from list of list using python

I am running the below code to remove duplicates from the element list of the list I am trying to remove element one by one from x = [['510','511','512'],['510','515','516']] when successfully removing element '515' and '516' final list will be x =[['510','511','512'],['510']] but 510 occured in x[0] so removed x[1] from list

remove_element = '515'
x = [['510','511','512'],['510','515','516']]
for i in x:
   if remove_element in i:
       i.remove(remove_element)
print(x)

Once final list [['510','511','512'],['510']] then remove list [['510','511','512']]

question from:https://stackoverflow.com/questions/65863126/remove-duplicate-element-from-list-of-list-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could first remove 515 as you have, and then loop through the contents of x[0] separately:

remove_element = '515'
x = [['510','511','512'],['510','515','516']]
for i in x:
   if remove_element in i:
       i .remove( remove_element )

for element in x[0]:  ##  ['510','511','512']
   if element in x[1]:  ##  ['510','515','516']
       x[1] .remove( element )

print(x)

or combine them into your remove list, then loop once:

#! /usr/bin/python3

remove = ['515']  ##  make this a list
x = [['510','511','512'],['510','515','516']]

##  add initial group of elements to your remove list
remove += x[0]  ##  ['515','510','511','512']

for element in remove:  ##  loop through list
   if element in x[1]:  ##  scan for duplicates
       x[1] .remove( element )

print(x)

[['510', '511', '512'], ['516']]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...