Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 find unique string
#1
i have a container of strings. it can be made available in whatever type is most convenient for the best solution, such as a list, or set. what i want to do is find if a given string is a "begins with" substring of exactly one string element of the container. an alternative is to find out the number of such matches or get a list of such matches. for example:
container = ('alignment','aliases')
ops = ('foo','ali','alia','bar')
for op in ops:
    result = find_matches(container,op)
    if len(result)==1:
        print(f'we have a match for "{op}" at "{result[0]}"')
        break
the output should be:
Output:
we have a match for "alia" at "aliases"
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
Just playing with Python 3.8:

>>> container = ('alignment','aliases')
>>> ops = ('foo','ali','alia','bar')
>>> [match[0] for op in ops if len(match := [cont for cont in container if cont.startswith(op)]) == 1]
['aliases']
>>> container = ('alignment', 'aliases', 'bartender')
>>> [match[0] for op in ops if len(match := [cont for cont in container if cont.startswith(op)]) == 1]
['aliases', 'bartender']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)