Home > other >  How to get python list element that contains 2 elements from another list
How to get python list element that contains 2 elements from another list

Time:03-16

list_a = ['BTC', 'ETH', 'ADA', 'DNT']
list_b = ['ab', 'BTCETH', 'ADAETH', 'DNTBTC', 'DNTXXX', 'BTCOOO']

result = ['BTCETH', 'ADAETH', 'DNTBTC']

The problem is as above, I have two lists and the second list contains various concatenated trading pairs from the first list. I want to only find the trading pairs (elements in list_b) that both appear in list_a. Thanks

CodePudding user response:

This is a very literal solution, regardless of the length of the strings in list_a:

list_a = ['BTC', 'ETH', 'ADA', 'DNT']
list_b = ['ab', 'BTCETH', 'ADAETH', 'DNTBTC', 'DNTXXX', 'BTCOOO']

result = [s for s in list_b if any(s.startswith(a) and s[len(a):] in list_a for a in list_a)]
print(result)

Output:

['BTCETH', 'ADAETH', 'DNTBTC']

If you want to avoid duplicates (e.g. 'BTCBTC'):

result = [
    s for s in list_b 
    if any(s.startswith(a) and s[len(a):] in list_a and s[len(a):] != a
    for a in list_a)]

CodePudding user response:

If you have many combinations and a lot of trading pairs, then you cold do something like this:

Calculate the set of all possible pairs. If this is done often you could store this data on disk.

Then filter list_b using your set.

from itertools import combinations

list_a = ['BTC', 'ETH', 'ADA', 'DNT']
list_b = ['ab', 'BTCETH', 'ADAETH', 'DNTBTC', 'DNTXXX', 'BTCOOO']


trading_pairs = set()
for (a, b) in combinations(set(list_a), r=2):
    # Handle the reverse case as well. e.g. BTCETH and ETHBTC
    trading_pairs.add(a   b)
    trading_pairs.add(b   a)


print([b for b in list_b if b in trading_pairs])

You could also use permutations instead:

from itertools import permutations
...

trading_pairs = set(map(''.join, permutations(set(list_a), r=2)))

If list_b has all unique values, you could calculate the intersection:

print(set(list_b) & trading_pairs)

As a one-liner:

print(set(list_b) & set(map(''.join, permutations(set(list_a), r=2))))
  • Related