Python: Return 2 ints for index in 2D lists given item
Try this: def index_2d(myList, v): for i, x in enumerate(myList): if v in x: return (i, x.index(v)) Usage: >>> index_2d(myList, 3) (1, 0)
Try this: def index_2d(myList, v): for i, x in enumerate(myList): if v in x: return (i, x.index(v)) Usage: >>> index_2d(myList, 3) (1, 0)
Using list comprehension: >>> lst = [[‘a’,’b’,’c’], [1,2,3], [‘x’,’y’,’z’]] >>> lst2 = [item[0] for item in lst] >>> lst2 [‘a’, 1, ‘x’]
Try a list comprehension: lst = [[] for _ in xrange(a)] See below: >>> a = 3 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], []] >>> a = 10 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], [], [], [], [], [], [], [], []] >>> … Read more
Use the power of the zip function and list comprehensions: list1 = [(‘a’, ), (‘b’, ‘c’), (‘d’, ‘e’), (‘f’, ‘g’, ‘h’) ] list2 = [(‘p’, ‘q’), (‘r’, ‘s’), (‘t’, ), (‘u’, ‘v’, ‘w’) ] print [a + b for a, b in zip(list1, list2)]
Using generator functions can make your example easier to read and improve performance. Python 2 Using the Iterable ABC added in 2.6: from collections import Iterable def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, basestring): for item in flatten(x): yield item else: yield x Python 3 In Python 3, basestring is … Read more
What you need is to nest another <ui:repeat> tag in your outer iteration: <ui:repeat value=”#{bean.listOfA}” var=”a”> … <ui:repeat value=”#{a.listOfB}” var=”b”> … </ui:repeat> </ui:repeat> The only thing left that is worth noting is that nested <ui:repeat> tags used to have problems with state management until Mojarra 2.1.15 version (details in jsf listener not called inside nested … Read more
Please take a look at the example NestedListHtml In this example, I take your code snippet list.html: <ul> <li>First <ol> <li>Second</li> <li>Second</li> </ol> </li> <li>First</li> </ul> And I parse it into an ElementList: // CSS CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true); // HTML HtmlPipelineContext htmlContext = new HtmlPipelineContext(null); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); htmlContext.autoBookmark(false); // Pipelines ElementList elements = new ElementList(); … Read more
Here’s a brute-force approach (it might be easier to understand): from itertools import chain def condense(*lists): # remember original positions positions = {} for pos, item in enumerate(chain(*lists)): if item not in positions: positions[item] = pos # condense disregarding order sets = condense_sets(map(set, lists)) # restore order result = [sorted(s, key=positions.get) for s in sets] … Read more
Just use a list comprehension: nested_lst_of_tuples = [tuple(l) for l in nested_lst] Demo: >>> nested_lst = [[‘tom’, ‘cat’], [‘jerry’, ‘mouse’], [‘spark’, ‘dog’]] >>> [tuple(l) for l in nested_lst] [(‘tom’, ‘cat’), (‘jerry’, ‘mouse’), (‘spark’, ‘dog’)]