1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Hi Guest, welcome to the TES Community!

    Connect with like-minded education professionals and have your say on the issues that matter to you.

    Don't forget to look at the how to guide.

    Dismiss Notice

How to find all occurrences of a string within a list when string is only part of the list item

Discussion in 'Design and technology' started by jainsaniya70, Aug 27, 2020.

Tags:
  1. jainsaniya70

    jainsaniya70 New commenter

    Using Python I cannot see a way to find instances within a list where the target string is a component (or partial) of a list item. I am looking for any instance of 'Volts' within all of the items in the list, whether volts is a full list item or there is a list item containing volts in some way. The list item could start or end with volts or even have volts contained in it in the middle of the item e.g. voltsOut, loadVolts, allVoltsSettings.

    Code:

    data =['Model','Name','Trans','Rx','OnPropertyChanged',
    'OnPropertyChangedAll','OtfMonitorEnabled','Overloads','PaletteBlackValue',
    'PaletteSizeFeature','PaletteSizeMax','PaletteValues','PaletteValuesArray',
    'PowerControlFeature','TransVolts','RecVolts','PropertyChanged','ReferenceEquals','Volts']

    indices =[i for i, x in enumerate(data)if x =="Volts"]
    print(indices)
    Desired outcome:

    I want it to show indices =[14,15,18]
     
  2. elder_cat

    elder_cat Lead commenter

    data = ['Model','Name','Trans','RX','OnPropertyChanged','OnPropertyChangedAll',
    'otfMonitorEnabled','Overloads','PaletteBlackValue','PaletteSizeFeature',
    'PaletteSizeMax','PaletteValues','PaletteValuesArray','PowerControlFeature',
    'TransVolts','RecVolts','PropertyChanged','ReferenceEquals','Volts']
    pattern = 'Volts'
    found = []
    for x in data:
    if pattern in x:
    found.append(data.index(x))
    print(found)

    Python Screenshot.png
     
  3. elder_cat

    elder_cat Lead commenter

    If you're set on using enumerate(), then this gives the same result:

    data = ['Model','Name','Trans','RX','OnPropertyChanged','OnPropertyChangedAll',
    'otfMonitorEnabled','Overloads','PaletteBlackValue','PaletteSizeFeature',
    'PaletteSizeMax','PaletteValues','PaletteValuesArray','PowerControlFeature',
    'TransVolts','RecVolts','PropertyChanged','ReferenceEquals','Volts']
    found = []
    for x, y in enumerate(data):
    if 'Volts' in y:
    found.append(x)
    print(found)




    [14, 15, 18]
     

Share This Page