list1 is the original list
list2 is the criterion list
list3 is the resulting list
Operation: if index (first element of each nested list) in list1 occurs in list2, delete this nested list and continue enumeration with the next element not in list2.
Example 1:
list1 = [[1,'a'],[2,'b'],[3,'c'],[4,'d'],[5,'e'],[6,'f'],[7,'g'], [8,'h']]
list2 = [3,4,5,7]
list3 = [[1,'a'],[2,'b'],[3,'f'],[4,'h']]
Example 2:
list1 = [[0,'do'],[1,'re'],[2,'mi'],[3,'fa'],[4,'sol'],[5,'la'],[6,'si']]
list2 = [1,3,5]
list3 = [[0,'do'],[1,'mi'],[2,'sol'],[3,'si']]
CodePudding user response:
Build two different iterators -- one with the unfiltered first elements, one with the second elements filtered according to the first element and list2
. Zip them together to build list3
.
>>> list1 = [[1,'a'],[2,'b'],[3,'c'],[4,'d'],[5,'e'],[6,'f'],[7,'g'], [8,'h']]
>>> list2 = [3,4,5,7]
>>> [list(z) for z in zip(next(zip(*list1)), (j for i, j in list1 if i not in list2))]
[[1, 'a'], [2, 'b'], [3, 'f'], [4, 'h']]
CodePudding user response:
Try:
list1 = [
[0, "do"],
[1, "re"],
[2, "mi"],
[3, "fa"],
[4, "sol"],
[5, "la"],
[6, "si"],
]
list2 = [1, 3, 5]
out = [b for a, b in list1 if a not in list2]
out = [[a, c] for (a, _), c in zip(list1, out)]
print(out)
Prints:
[[0, 'do'], [1, 'mi'], [2, 'sol'], [3, 'si']]
CodePudding user response:
You can use list comprehensions like so:
list1 = [[1,'a'],[2,'b'],[3,'c'],[4,'d'],[5,'e'],[6,'f'],[7,'g'], [8,'h']]
list2 = [3,4,5,7]
temp = [i for i in list1 if not i[0] in list2]
list3 = [[i 1, temp[i][1]] for i in range(len(temp))]
print(list3)
Output:
[[1, 'a'], [2, 'b'], [3, 'f'], [4, 'h']]
CodePudding user response:
Obviously there are plenty of ways to make this happen, here's one.
def yourFunctionName(list1,list2):
result = []
n = 1
for element in list1:
if not element[0] in list2:
result.append([n,element[1]])
return result
CodePudding user response:
You can accomplish this with a list comprehension, using list1 and list2 from the first example:
list3 = [[i list1[0][0], elem[1]] for i, elem in enumerate(e for e in list1 if e[0] not in list2)]
print(list3)
The idea is that I get rid of all the lists in the criterion list first, and then I re-enumerate them based on the first element in list1.
Output:
[[1, 'a'], [2, 'b'], [3, 'f'], [4, 'h']]