mudi loodi
mudi loodi

Reputation: 113

How to compare strings within a list-of-lists?

I have the following list

lst =[['A', 'BA'], ['B', 'CB'], ['C', 'AC'], ['D', 'ED']].

I want to check if the first element in a given list is found in the second element of the previous list. If that is the case then take the second element of the list and add it to the second element in the previous list.

Eg. 'B' is found in 'BA', therefore the first list should look like this ['A', 'BACB'].

I have tried different things, but the following is the closest to the desired result:

for i, j in enumerate(lst[1:]):
    if ''.join((set(j[0])).intersection(lst[i][1])):
        lst[i][1] += j[1]

> output: [['A', 'BACB'], ['B', 'CBAC'], ['C', 'AC'], ['D', 'ED']]

The desired result looks like this:

[['A', 'BACB'], ['B', 'CBAC'], ['C', 'ACBACB'], ['D', 'ED']]

Upvotes: 0

Views: 124

Answers (1)

Guf
Guf

Reputation: 249

It is unclear whether the following code can cover all test cases.

# -*- coding:utf-8 -*-
lst = [['A', 'BA'], ['B', 'CB'], ['C', 'AC'], ['D', 'ED']]
# lst_map = dict(lst)
lst_map = {i[0]: i[1] for i in lst}
for k, v in lst_map.items():
    for c in v:
        if c != k:
            lst_map[k] += lst_map.get(c, "")
result = [[k, v] for k, v in lst_map.items()]
print(result)
# Output [['A', 'BACB'], ['B', 'CBAC'], ['C', 'ACBACB'], ['D', 'ED']]

Upvotes: 2

Related Questions