0

Sorry if the question is a little confusing, but basically I have the following data:

useable = ['osc_1_', 'osc_2_', 'osc_3_', 'sample_', 'filter_1_', 'filter_2_', 'filter_fx_', 'lfo_1_', 'lfo_2_', 'lfo_3_', 'lfo_4_', 'lfo_5_', 'lfo_6_', 'lfo_7_', 'lfo_8_', 'random_1_', 'random_2_', 'random_3_', 'random_4_', 'env_1_', 'env_2_', 'env_3_', 'env_4_', 'env_5_', 'env_6_', 'chorus_', 'compressor', 'delay', 'distortion', 'phaser', 'flanger', 'reverb', 'equalizer']

I also have a string value: x = 'filter_fx_formant_x'

I'm using the following function to return 'True' if x contains a value that can be found in useable,

if any(useable in x for useable in useable):

ex: 'filter_fx_' is in both a substring of x and a value in useable.

Now here's my question: How can I get the index value of the item that can be found in a substring of x?

Is there a better way other than any()? Am I missing something obvious? Let me know if you can think of anything.

SlavaCat
  • 101
  • 6

4 Answers4

0

this You can use if You want to get the index:

useable = ['osc_1_', 'osc_2_', 'osc_3_', 'sample_', 'filter_1_', 'filter_2_', 'filter_fx_', 'lfo_1_', 'lfo_2_', 'lfo_3_', 'lfo_4_', 'lfo_5_', 'lfo_6_', 'lfo_7_', 'lfo_8_', 'random_1_', 'random_2_', 'random_3_', 'random_4_', 'env_1_', 'env_2_', 'env_3_', 'env_4_', 'env_5_', 'env_6_', 'chorus_', 'compressor', 'delay', 'distortion', 'phaser', 'flanger', 'reverb', 'equalizer']
x = 'filter_fx_formant_x'

for index, item in enumerate(useable):
    if item in x:
        print(index, item)

Matiiss
  • 5,970
  • 2
  • 12
  • 29
0

If your concern is to use any(), one way to implement your logic would be by the combination of map and str.contains()

any(map(x.__contains__, useable))

Output:

True

if you just want to get the first index if x contains substring from the list, you can implement same thing in an if conditional

>>mask = list(map(x.__contains__, useable))
>>if any(mask):
    print(mask.index(True))
    
6
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

This is what next+enumerate allows:

try:
    idx, found = next((i, useable) for i, useable in enumerate(useables) if useable in x):
except StopIteration:
    # No hits found
else:
    # idx is now the index of the first item to hit, found is the value

If you're guaranteed to have a hit for whatever reason, the try/except/else isn't needed.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
-1

It should be like this instead:

if (any(substring in x for substring in useable)):
scorpi03
  • 69
  • 3
  • You added unnecessary additional parentheses, and changed a single variable name, changing no behavior at all (admittedly, the original reuse of names was suboptimal, but it didn't break anything). You did not answer the question at all. – ShadowRanger Apr 02 '21 at 01:19