Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list of string combinations
#6
from itertools import product
import re

def string_combos(s):
    # get all expressions inside brackets into a list
    brackets = re.findall(r'{(.+?)}', s)

    # remove comas 
    joined_chars_list = [''.join(b.split(',')) for b in brackets]

    # In the above line the b.split(',') could be turned into another
    # list comprehension to remove whitespace if it is acceptable as
    # a part of input string

    # E.g. if this is acceptable:
    # string_combos('{a, b}{ c , d}{ e,   f}')

    # Then use something like:
    # [char_part.strip() for char_part in b.split(',')]
    
    return [''.join(p) for p in product(*joined_chars_list)] # copy of what scidam posted but I find this way easier to read than "list(map(" way
    
result = string_combos('{a,b}{c,d}{e,f}')
print(result)
Output:
['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
Reply


Messages In This Thread
list of string combinations - by Skaperen - May-21-2019, 01:25 AM
RE: list of string combinations - by scidam - May-21-2019, 01:39 AM
RE: list of string combinations - by Skaperen - May-21-2019, 08:14 PM
RE: list of string combinations - by michalmonday - May-21-2019, 08:53 PM
RE: list of string combinations - by Skaperen - May-22-2019, 01:14 AM
RE: list of string combinations - by michalmonday - May-22-2019, 01:43 AM
RE: list of string combinations - by Skaperen - May-22-2019, 05:03 AM
RE: list of string combinations - by michalmonday - May-22-2019, 11:46 AM
RE: list of string combinations - by Skaperen - May-22-2019, 01:18 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding combinations of list of items (30 or so) LynnS 1 949 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  How can I find all combinations with a regular expression? AlekseyPython 0 1,736 Jun-23-2021, 04:48 PM
Last Post: AlekseyPython
  All possible combinations CODEP 2 1,950 Dec-01-2020, 06:10 PM
Last Post: deanhystad
  Triplet Combinations of All Values quest 2 2,081 Nov-05-2020, 09:22 AM
Last Post: quest
  All possible combinations of multiplications Shreya10o 0 1,721 May-23-2020, 07:45 AM
Last Post: Shreya10o
  counting items in a list of number combinations Dixon 2 2,143 Feb-19-2020, 07:06 PM
Last Post: Dixon
  Python program that list all possible football outcome combinations lukorir 5 9,142 Oct-17-2019, 04:05 AM
Last Post: steve_shambles
  Do something with all possible combinations of a list 3Pinter 7 4,312 Sep-11-2019, 08:19 AM
Last Post: perfringo
  Python to iterate a number of possible combinations teflon 4 4,071 Apr-24-2019, 03:00 AM
Last Post: scidam
  I converted string to 'list', but it doesn't look like a list! mrapple2020 3 3,355 Apr-07-2019, 02:34 PM
Last Post: mrapple2020

Forum Jump:

User Panel Messages

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