Python Forum
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"
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  system-wide unique incrementing string or number Skaperen 11 4,010 Jul-08-2020, 08:10 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020