Lenny D.
Lenny D.

Reputation: 298

Removing a string from a list inside a list of lists

What I'm trying to achieve here in a small local test is to iterate over an array of strings, which are basically arrays of strings inside a parent array.

I'm trying to achieve the following...

So far I've tried the following, but I'm struggling with an error that I don't know where it does come from...

lines = map(lambda l: str.replace(l, "\n", ""),
            list(open("PATH", 'r')))

splitLines = map(lambda l: l.split(','), lines)

for line in splitLines:
    for keyword in line:
        print(list(splitLines).remove(keyword))

But I'm getting the following error...

ValueError: list.remove(x): x not in list

Which isn't true as 'x' isn't a string included in any of the given test arrays.

SAMPLE INPUT (Comma separated lines in a text file, so I get an array of strings per line):

[['a', 'b', 'c'], ['e', 'f', 'g'], ['b', 'q', 'a']]

SAMPLE OUTPUT:

[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]

Upvotes: 1

Views: 70

Answers (2)

user3483203
user3483203

Reputation: 51155

You can keep track of previously seen strings using a set for fast lookups, and using a simple list comprehension to add elements not found in the previously seen set.

prev = set()
final = []
for i in x:
  final.append([j for j in i if j not in prev])
  prev = prev.union(set(i))

print(final)

Output:

[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]

Upvotes: 2

Ken T
Ken T

Reputation: 2553

inputlist = [['a', 'b', 'c'], ['e', 'f', 'g'], ['b', 'q', 'a']]
scanned=[]

res=[]
for i in inputlist:
    temp=[]
    for j in i:
        if j in scanned:
            pass
        else:
            scanned.append(j)
            temp.append(j)
    res.append(temp)

[['a', 'b', 'c'], ['e', 'f', 'g'], ['q']]

Upvotes: 1

Related Questions