Search Results

Search found 58 results on 3 pages for 'itertools'.

Page 1/3 | 1 2 3  | Next Page >

  • In python: how to apply itertools.product to elements of a list of lists

    - by Guilherme Rocha
    I have a list of arrays and I would like to get the cartesian product of the elements in the arrays. I will use an example to make this more concrete... itertools.product seems to do the trick but I am stuck in a little detail. arrays = [(-1,+1), (-2,+2), (-3,+3)]; If I do cp = list(itertools.product(arrays)); I get cp = cp0 = [((-1, 1),), ((-2, 2),), ((-3, 3),)] But what I want to get is cp1 = [(-1,-2,-3), (-1,-2,+3), (-1,+2,-3), (-1,+2,+3), ..., (+1,+2,-3), (+1,+2,+3)]. I have tried a few different things: cp = list(itertools.product(itertools.islice(arrays, len(arrays)))); cp = list(itertools.product(iter(arrays, len(arrays)))); They all gave me cp0 instead of cp1. Any ideas? Thanks in advance.

    Read the article

  • Pythonic / itertools way to go through a dict?

    - by dmd
    def reportCSV(t): ret = '' for ev in t: for p in t[ev]: for w in t[ev][p]: ret += ','.join((ev, p, w, t[ev][p][w])) + '\n' return ret What is a more pythonic way to do this, e.g. using itertools or the like? In this case I'm just writing it out to a CSV file. t is a dict t[ev] is a dict t[ev][p] is a dict t[ev][p][w] is a float I'm not sure how I'd use itertools.product in this case.

    Read the article

  • itertools.product eliminating repeated reversed tuples

    - by genclik27
    I asked a question yesterday and thanks to Tim Peters, it is solved. The question is here; itertools.product eliminating repeated elements The new question is further version of this. This time I will generate tuples inside of tuples. Here is an example; lis = [[(1,2), (3,4)], [(5,2), (1,2)], [(2,1), (1,2)]] When I use it in itertools.product function this is what I get, ((1, 2), (5, 2), (2, 1)) ((1, 2), (5, 2), (1, 2)) ((1, 2), (1, 2), (2, 1)) ((1, 2), (1, 2), (1, 2)) ((3, 4), (5, 2), (2, 1)) ((3, 4), (5, 2), (1, 2)) ((3, 4), (1, 2), (2, 1)) ((3, 4), (1, 2), (1, 2)) I want to change it in a way that if a sequence has (a,b) inside of it, then it can not have (b,a). In this example if you look at this sequence ((3, 4), (1, 2), (2, 1)) it has (1,2) and (2,1) inside of it. So, this sequence ((3, 4), (1, 2), (2, 1)) should not be considered in the results. As I said, I asked similar question before, in that case it was not considering duplicate elements. I try to adapt it to my problem. Here is modified code. Changed parts in old version are taken in comments. def reverse_seq(seq): s = [] for i in range(len(seq)): s.append(seq[-i-1]) return tuple(s) def uprod(*seqs): def inner(i): if i == n: yield tuple(result) return for elt in sets[i] - reverse: #seen.add(elt) rvrs = reverse_seq(elt) reverse.add(rvrs) result[i] = elt for t in inner(i+1): yield t #seen.remove(elt) reverse.remove(rvrs) sets = [set(seq) for seq in seqs] n = len(sets) #seen = set() reverse = set() result = [None] * n for t in inner(0): yield t In my opinion this code should work but I am getting error for the input lis = [[(1,2), (3,4)], [(5,2), (1,2)], [(2,1), (1,2)]]. I could not understand where I am wrong. for i in uprod(*lis): print i Output is, ((1, 2), (1, 2), (1, 2)) Traceback (most recent call last): File "D:\Users\SUUSER\workspace tree\sequence_covering _array\denemeler_buraya.py", line 39, in <module> for i in uprod(*lis): File "D:\Users\SUUSER\workspace tree\sequence_covering _array\denemeler_buraya.py", line 32, in uprod for t in inner(0): File "D:\Users\SUUSER\workspace tree\sequence_covering _array\denemeler_buraya.py", line 22, in inner for t in inner(i+1): File "D:\Users\SUUSER\workspace tree\sequence_covering _array\denemeler_buraya.py", line 25, in inner reverse.remove(rvrs) KeyError: (2, 1) Thanks,

    Read the article

  • Itertools group by functionality

    - by Nil
    I want to group by on dict key >>> x [{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}] >>> [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])] [(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])] This must group on key 10 :(

    Read the article

  • What are the Ruby equivalent of Python itertools, esp. combinations/permutations/groupby?

    - by Amadeus
    Python's itertools module provides a lots of goodies with respect to processing an iterable/iterator by use of generators. For example, permutations(range(3)) --> 012 021 102 120 201 210 combinations('ABCD', 2) --> AB AC AD BC BD CD [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D What are the equivalent in Ruby? By equivalent, I mean fast and memory efficient (Python's itertools module is written in C).

    Read the article

  • How do I use Python's itertools.groupby()?

    - by James Sulak
    I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function. What I'm trying to do is this: take a list - in this case, the children of an objectified lxml element - divide it into groups based on some criteria, and then later iterate over each of these groups separately. I've reviewed the documentation (http://docs.python.org/lib/itertools-functions.html), and the examples, (http://docs.python.org/lib/itertools-example.html), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of itertools.groupby()? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.

    Read the article

  • Combinatorial optimisation of a distance metric

    - by Jose
    I have a set of trajectories, made up of points along the trajectory, and with the coordinates associated with each point. I store these in a 3d array ( trajectory, point, param). I want to find the set of r trajectories that have the maximum accumulated distance between the possible pairwise combinations of these trajectories. My first attempt, which I think is working looks like this: max_dist = 0 for h in itertools.combinations ( xrange(num_traj), r): for (m,l) in itertools.combinations (h, 2): accum = 0. for ( i, j ) in itertools.izip ( range(k), range(k) ): A = [ (my_mat[m, i, z] - my_mat[l, j, z])**2 \ for z in xrange(k) ] A = numpy.array( numpy.sqrt (A) ).sum() accum += A if max_dist < accum: selected_trajectories = h This takes forever, as num_traj can be around 500-1000, and r can be around 5-20. k is arbitrary, but can typically be up to 50. Trying to be super-clever, I have put everything into two nested list comprehensions, making heavy use of itertools: chunk = [[ numpy.sqrt((my_mat[m, i, :] - my_mat[l, j, :])**2).sum() \ for ((m,l),i,j) in \ itertools.product ( itertools.combinations(h,2), range(k), range(k)) ]\ for h in itertools.combinations(range(num_traj), r) ] Apart from being quite unreadable (!!!), it is also taking a long time. Can anyone suggest any ways to improve on this?

    Read the article

  • algorithm for python itertools.permutations

    - by zaharpopov
    Can someone please explain algorithm for itertools.permutations routine in Python standard lib 2.6? I see its code in the documentation but don't undestand why it work? Thanks Code is: def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return

    Read the article

  • python input for itertools.product

    - by user364249
    Looking for a way to simulate nested loops (or a cartesian product) i came across the itertools.product function. i need a function or piece of code that receive a list of integers as input and returns a specific generator. example: input = [3,2,4] - gen = product(xrange(3),xrange(2),xrange(4)) or input = [2,4,5,6] - gen = product(xrange(2),xrange(4),xrange(5),xrange(6)) as the size of the lists varies i am very confused in how to do that without the need of a lot of precoding based on a crazy amount of ifs and the size of the list. also is there a difference in calling product(range(3)) or product(xrange(3))?

    Read the article

  • Is there a neater way to get the first occurrence of something?

    - by Phil H
    I have a list which contains a number of things: lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next? first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista)) I did use [item for item in lista if len(item)>2][0] at first, but that requires python to generate the entire list first.

    Read the article

  • efficient list mapping in python

    - by Joey
    Hi everyone, I have the following input: input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)] and trying to have the following output: outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]] outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse} Any tips on how to handle given with scalability in mind (var input can get really large).

    Read the article

  • Fast iterating over first n items of an iterable in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of a list, and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_somethin(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • Fast iterating over first n items of an iterable (not a list) in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_something(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • Why doesn't Python have a "flatten" function for lists?

    - by Hubro
    Erlang and Ruby both come with functions for flattening arrays. It seems like such a simple and useful tool to add to a language. One could do this: >>> mess = [[1, [2]], 3, [[[4, 5]], 6]] >>> mess.flatten() [1, 2, 3, 4, 5, 6] Or even: >>> import itertools >>> mess = [[1, [2]], 3, [[[4, 5]], 6]] >>> list(itertools.flatten(mess)) [1, 2, 3, 4, 5, 6] Instead, in Python, one has to go through the trouble of writing a function for flattening arrays from scratch. This seems silly to me, flattening arrays is such a common thing to do. It's like having to write a custom function for concatenating two arrays. I have Googled this fruitlessly, so I'm asking here; is there a particular reason why a mature language like Python 3, which comes with a hundred thousand various batteries included, doesn't provide a simple method of flattening arrays? Has the idea of including such a function been discussed and rejected at some point?

    Read the article

  • How to generate all variations with repetitions of a string?

    - by Svenstaro
    I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach. I'm quite surprised that I wasn't able to find a solution to this problem anywhere on the web or on StackOverflow. I've come up with a Python script that does what I want as well: import itertools variations = itertools.product('ab', repeat=4) for variations in variations: variation_string = "" for letter in variations: variation_string += letter print variation_string Output: aaaa aaab aaba aabb abaa abab abba abbb baaa baab baba babb bbaa bbab bbba bbbb Ideally I'd like a C++ program that can produce the exact output, taking the exact same parameters. This is for learning purposes, it isn't homework. I wish my homework was like that.

    Read the article

  • Python: Memory usage and optimization when modifying lists

    - by xApple
    The problem My concern is the following: I am storing a relativity large dataset in a classical python list and in order to process the data I must iterate over the list several times, perform some operations on the elements, and often pop an item out of the list. It seems that deleting one item out of a Python list costs O(N) since Python has to copy all the items above the element at hand down one place. Furthermore, since the number of items to delete is approximately proportional to the number of elements in the list this results in an O(N^2) algorithm. I am hoping to find a solution that is cost effective (time and memory-wise). I have studied what I could find on the internet and have summarized my different options below. Which one is the best candidate ? Keeping a local index: while processingdata: index = 0 while index < len(somelist): item = somelist[index] dosomestuff(item) if somecondition(item): del somelist[index] else: index += 1 This is the original solution I came up with. Not only is this not very elegant, but I am hoping there is better way to do it that remains time and memory efficient. Walking the list backwards: while processingdata: for i in xrange(len(somelist) - 1, -1, -1): dosomestuff(item) if somecondition(somelist, i): somelist.pop(i) This avoids incrementing an index variable but ultimately has the same cost as the original version. It also breaks the logic of dosomestuff(item) that wishes to process them in the same order as they appear in the original list. Making a new list: while processingdata: for i, item in enumerate(somelist): dosomestuff(item) newlist = [] for item in somelist: if somecondition(item): newlist.append(item) somelist = newlist gc.collect() This is a very naive strategy for eliminating elements from a list and requires lots of memory since an almost full copy of the list must be made. Using list comprehensions: while processingdata: for i, item in enumerate(somelist): dosomestuff(item) somelist[:] = [x for x in somelist if somecondition(x)] This is very elegant but under-the-cover it walks the whole list one more time and must copy most of the elements in it. My intuition is that this operation probably costs more than the original del statement at least memory wise. Keep in mind that somelist can be huge and that any solution that will iterate through it only once per run will probably always win. Using the filter function: while processingdata: for i, item in enumerate(somelist): dosomestuff(item) somelist = filter(lambda x: not subtle_condition(x), somelist) This also creates a new list occupying lots of RAM. Using the itertools' filter function: from itertools import ifilterfalse while processingdata: for item in itertools.ifilterfalse(somecondtion, somelist): dosomestuff(item) This version of the filter call does not create a new list but will not call dosomestuff on every item breaking the logic of the algorithm. I am including this example only for the purpose of creating an exhaustive list. Moving items up the list while walking while processingdata: index = 0 for item in somelist: dosomestuff(item) if not somecondition(item): somelist[index] = item index += 1 del somelist[index:] This is a subtle method that seems cost effective. I think it will move each item (or the pointer to each item ?) exactly once resulting in an O(N) algorithm. Finally, I hope Python will be intelligent enough to resize the list at the end without allocating memory for a new copy of the list. Not sure though. Abandoning Python lists: class Doubly_Linked_List: def __init__(self): self.first = None self.last = None self.n = 0 def __len__(self): return self.n def __iter__(self): return DLLIter(self) def iterator(self): return self.__iter__() def append(self, x): x = DLLElement(x) x.next = None if self.last is None: x.prev = None self.last = x self.first = x self.n = 1 else: x.prev = self.last x.prev.next = x self.last = x self.n += 1 class DLLElement: def __init__(self, x): self.next = None self.data = x self.prev = None class DLLIter: etc... This type of object resembles a python list in a limited way. However, deletion of an element is guaranteed O(1). I would not like to go here since this would require massive amounts of code refactoring almost everywhere.

    Read the article

  • vtk glyphs 3D, indenpently color and rotation

    - by user3684219
    I try to display thanks to vtk (python wrapper) several glyphs in a scene with each their own colour and rotation. Unfortunately, just the rotation (using vtkTensorGlyph) is taken in consideration by vtk. Reversely, just color is taken in consideration when I use a vtkGlyph3D. Here is a ready to use piece of code with a vtkTensorGlyph. Each cube should have a random color but there all will be in the same color. I read and read again the doc of vtk but I found no solution. Thanks in advance for any idea #!/usr/bin/env python # -*- coding: utf-8 -*- import vtk import scipy.linalg as sc import random as ra import numpy as np import itertools points = vtk.vtk.vtkPoints() # where to locate each glyph in the scene tensors = vtk.vtkDoubleArray() # rotation for each glyph tensors.SetNumberOfComponents(9) colors = vtk.vtkUnsignedCharArray() # should be the color for each glyph colors.SetNumberOfComponents(3) # let's make 10 cubes in the scene for i in range(0, 50, 5): points.InsertNextPoint(i, i, i) # position of a glyph colors.InsertNextTuple3(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255) ) # pick random color rot = list(itertools.chain(*np.reshape(sc.orth(np.random.rand(3, 3)).transpose(), (1, 9)).tolist())) # random rotation matrix (row major) tensors.InsertNextTuple9(*rot) polydata = vtk.vtkPolyData() # create the polydatas polydata.SetPoints(points) polydata.GetPointData().SetTensors(tensors) polydata.GetPointData().SetScalars(colors) cubeSource = vtk.vtkCubeSource() cubeSource.Update() glyphTensor = vtk.vtkTensorGlyph() glyphTensor.SetColorModeToScalars() # is it really work ? try: glyphTensor.SetInput(polydata) except AttributeError: glyphTensor.SetInputData(polydata) glyphTensor.SetSourceConnection(cubeSource.GetOutputPort()) glyphTensor.ColorGlyphsOn() # should not color all cubes independently ? glyphTensor.ThreeGlyphsOff() glyphTensor.ExtractEigenvaluesOff() glyphTensor.Update() # next is usual vtk code mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphTensor.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.SetBackground(0.2, 0.5, 0.3) ren.AddActor(actor) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) iren.SetRenderWindow(renwin) renwin.Render() iren.Initialize() renwin.Render() iren.Start()

    Read the article

  • Listing serial (COM) ports on Windows?

    - by Eli Bendersky
    Hello, I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's this post about using WMI, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET. I currently know of two other approaches: Reading the information in the HARDWARE\\DEVICEMAP\\SERIALCOMM registry key. This looks like a great option, but is it robust? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports. Tryint to call CreateFile on COMN with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method. Any other methods/ideas/experience to share? Edit: by the way, here's a simple Python implementation of reading the port names from registry: import _winreg as winreg import itertools def enumerate_serial_ports(): """ Uses the Win32 registry to return a iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break

    Read the article

  • Pairs from single list

    - by Apalala
    Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google: pairs = zip(t[::2], t[1::2]) I thought that was pythonic enough, but after a recent discussion involving idioms versus efficiency, I decided to do some tests: import time from itertools import islice, izip def pairs_1(t): return zip(t[::2], t[1::2]) def pairs_2(t): return izip(t[::2], t[1::2]) def pairs_3(t): return izip(islice(t,None,None,2), islice(t,1,None,2)) A = range(10000) B = xrange(len(A)) def pairs_4(t): # ignore value of t! t = B return izip(islice(t,None,None,2), islice(t,1,None,2)) for f in pairs_1, pairs_2, pairs_3, pairs_4: # time the pairing s = time.time() for i in range(1000): p = f(A) t1 = time.time() - s # time using the pairs s = time.time() for i in range(1000): p = f(A) for a, b in p: pass t2 = time.time() - s print t1, t2, t2-t1 These were the results on my computer: 1.48668909073 2.63187503815 1.14518594742 0.105381965637 1.35109519958 1.24571323395 0.00257992744446 1.46182489395 1.45924496651 0.00251388549805 1.70076990128 1.69825601578 If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected. Is there another, "better" way of traversing a list in pairs? Note that if the list has an odd number of elements then the last one will not be in any of the pairs. Which would be the right way to ensure that all elements are included? I added these two suggestions from the answers to the tests: def pairwise(t): it = iter(t) return izip(it, it) def chunkwise(t, size=2): it = iter(t) return izip(*[it]*size) These are the results: 0.00159502029419 1.25745987892 1.25586485863 0.00222492218018 1.23795199394 1.23572707176 Results so far Most pythonic and very efficient: pairs = izip(t[::2], t[1::2]) Most efficient and very pythonic: pairs = izip(*[iter(t)]*2) It took me a moment to grok that the first answer uses two iterators while the second uses a single one. To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (None) that gets paired with the previous last element, something that can be achieved with itertools.izip_longest().

    Read the article

  • Python 2.7.3 memory error

    - by Tom Baker
    I have a specific case with python code. Every time I run the code, the RAM memory is increasing until it reaches 1.8 gb and crashes. import itertools import csv import pokersleuth cards = ['2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Ts', 'Js', 'Qs', 'Ks', 'As', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh', 'Qh', 'Kh', 'Ah', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc', 'Qc', 'Kc', 'Ac', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Td', 'Jd', 'Qd', 'Kd', 'Ad'] flop = itertools.combinations(cards,3) a1 = 'Ks' ; a2 = 'Qs' b1 = 'Jc' ; b2 = 'Jd' cards1 = a1+a2 cards2 = b1+b2 number = 0 n=0 m=0 for row1 in flop: if (row1[0] <> a1 and row1[0] <>a2 and row1[0] <>b1 and row1[0] <>b2) and (row1[1] <> a1 and row1[1] <>a2 and row1[1] <>b1 and row1[1] <>b2) and (row1[2] <> a1 and row1[2] <> a2 and row1[2] <> b1 and row1[2] <> b2): for row2 in cards: if (row2 <> a1 and row2 <> a2 and row2 <> b1 and row2 <> b2 and row2 <> row1[0] and row2 <> row1[1] and row2 <> row1[2]): s = pokersleuth.compute_equity(row1[0]+row1[1]+row1[2]+row2, (cards1, cards2)) if s[0]>=0.5: number +=1 del s[:] del s[:] print number/45.0 number = 0 n+=1

    Read the article

  • No module named difflib

    - by bugbug
    I want to execute python code from C# with following code. static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py"); source.Execute(); } I have the problem at line source.Execute(), I got error "No module named difflib". What is wrong in my code? This is my python code (extracter.py). import re import itertools import difflib print "Hello"

    Read the article

  • All possible permutations of a set of lists in Python

    - by Ian Davis
    In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations: For example [ [ a, b, c], [d], [e, f] ] I want [ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ] Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance

    Read the article

  • Problem with list slice syntax in python

    - by Dingle
    The extended indexing syntax is mentioned in python's doc. slice([start], stop[, step]) Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator. a[start:stop:step] works as described. But what about the second one? How is it used?

    Read the article

1 2 3  | Next Page >