Python Forum
List all possibilities of a nested-list by flattened lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List all possibilities of a nested-list by flattened lists
#1
S = [['he', 'she'], 'has', ['1', '2'], 'watch']

A list inside the list S indicates a possibility of a statement.
So there are four possibilities here:

'he has 1 watch'
'he has 2 watch'
'she has 1 watch'
'she has 2 watch'

(Just for demonstration so it doesn't need to be grammatically correct)

I'm sure there's a simple way to list out all possibilities, but how? Any help would be much appreciated!
Reply
#2
Got that!

import itertools
S = [['he', 'she'], ['has'], ['1', '2'], ['watch']]
print(list(itertools.product(*S)))

Output: [('he', 'has', '1', 'watch'), ('he', 'has', '2', 'watch'), ('she', 'has', '1', 'watch'), ('she', 'has', '2', 'watch')]
Gribouillis likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,183 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,554 May-01-2023, 09:06 PM
Last Post: deanhystad
  user input values into list of lists tauros73 3 1,075 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,078 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 1,855 Oct-26-2022, 04:03 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,661 Oct-01-2022, 07:15 PM
Last Post: Skaperen
Question Keyword to build list from list of objects? pfdjhfuys 3 1,578 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Split a number to list and list sum must be number sunny9495 5 2,307 Apr-28-2022, 09:32 AM
Last Post: Dexty
  Updating nested dict list keys tbaror 2 1,291 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Python Program to Find the Total Sum of a Nested List vlearner 8 4,939 Jan-23-2022, 07:20 PM
Last Post: menator01

Forum Jump:

User Panel Messages

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