loops - Advanced (maybe) selection rule for lists in Python -
given list
list_ = [a,a,b,b,b,a,b,a,b,b,...,b]
and 2 other lists
l_a = [v1,v2,...,vn] l_b = [w1,w2,...,wn].
the first element of list_ "a
". remaining elements can mixed between being "a
" , "b
" in random way.
now, starting first element in list_ (which "a"):
- take elements
l_a
until hit "b
" (in case: [v1, v2]). form "v1+v2
" key dictionary (the corresponding value in step 2. below). our current key. - take elements l_b until hit "a" (in case [w1,w2,w3]). store "
w1 + w2 + w3
" value under current key. - repeat.
of course, there lot of loop stuff going on tried, gets difficult bookkeep , makes me think there better way nesting loops.
question: so, put, how do in efficient way?
thank you
maybe give ideas.
what want group repeated items (itertools.groupby great that) remove items head of list (you leave lists alone , maintain index of current position , slicing).
import itertools import random import collections choices = ['a', 'b'] list_ = [random.choice(choices) _ in range(30)] l_a = collections.deque([random.randint(1, 100) _ in range(list_.count('a'))]) l_b = collections.deque([random.randint(1, 100) _ in range(list_.count('b'))]) # above build sample data. # can wrap existing l_a, l_b lists in collections.deque # make dictionary holds 2 dequeues keyed character find in list_ lists_by_char = {'a': l_a, 'b': l_b} # print out make sure aren't cheating print(list_) print(l_a) print(l_b) k, g in itertools.groupby(list_): # k letter 'a' or 'b' # g items in _grouper. can call list on actual items. care length of list. items = [lists_by_char.get(k).popleft() _ in range(len(list(g)))] # call popleft on deque matching our current character many times our list of characters long. print(k, items)
example output - vary each time run it
['a', 'a', 'b', 'b', 'b', 'a', 'a', 'a', 'b', 'a', 'b', 'b', 'a', 'b', 'b', 'b', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'a', 'a', 'b', 'b', 'b', 'a', 'a'] deque([36, 61, 7, 17, 25, 76, 2, 72, 15, 33, 1, 53, 54, 49, 29, 68]) deque([55, 95, 97, 24, 72, 14, 54, 98, 91, 98, 57, 56, 40, 17]) [36, 61] b [55, 95, 97] [7, 17, 25] b [24] [76] b [72, 14] [2] b [54, 98, 91] [72, 15, 33, 1, 53] b [98, 57] [54, 49] b [56, 40, 17] [29, 68]
Comments
Post a Comment