for eg if sequence 1 : <1,3,5> and sequence 2 : <2,6,8,11,12>
than the result should be <1,2,3,6,5,8,11,12>
I tried to solve it using loops but what I am getting is a repeated structure
i=0
j=0
N=len(L1)
M=len(L2)
L=[]
turn=True
while(i<N and j<M):
if turn:
L.append(L1[i])
i+=1
else:
L.append(L2[j])
j+=1
turn=!turn
while(i<N):
L.append(L1[i])
i+=1
while(j<M):
L.append(L2[j])
j+=1
print(L)
THis can do the trick for you What Is being done is That I am keeping a boolean Turn to Alternate turns to select from the two arrays If You have any doubt regarding the loop logic I can elaborate a little. simple turn= !turn => ALternates turns on each iteration
I'd be surprised if there isn't a better way to do it, but one way to do it would be like this:
from itertools import zip_longest
seq_1 = [1,3,5]
seq_2 = [2,6,8,11,12]
seq_3 = []
for a, b in zip_longest(seq_1, seq_2): # -> (1, 2) (3, 6) (5, 8) (None, 11) (None, 12)
if a:
seq_3.append(a)
if b:
seq_3.append(b)
This should do the trick.
Explanation:
a = [1,3,5]
b = [2,4]
zip_longest(a,b) -> (1,2), (3,4), (5, None)
chain.from_iterable(l) -> 1,2,3,4,5,None
Followed by list comprehension.
from itertools import chain, zip_longest
l = [i for i in chain.from_iterable(zip_longest(a,b)) if i]
This code gives you a list of sorted numbers based on input.
x1,x2=[1,3,5],[2,6,8,11,12]
print(sorted(x1+x2))
I have been able to join strings as such:
string_right = list(range(1,100))
string_left = ['AAA','BBB', "CCC"]
combination = []
for i in headers_right:
merged1 = string_left[0] + ' ' + str(i)
merged2 = string_left[1] + ' ' + str(i)
merged3 = string_left[2] + ' ' + str(i)
combination.append(merged1)
combination.append(merged2)
combination.append(merged3)
Is there a more efficient way to do it? I would like to avoid the for loop.
I was thinking about something like zip or enumerate, but they seem to create tuples instead of concatenating strings.
The result should look like:
['AAA1','BBB1', "CCC1", 'AAA2','BBB2', "CCC2",...,'AAA100','BBB100', "CCC100"]
Thanks so much in advance!
You can use itertools.product for this, which essentially gives a cartesian product of the two lists, and then we take each element from that product, and join the two elements.
For example
In [2]: from itertools import product
In [1]: string_right = range(1,3)
...: string_left = ['AAA','BBB', "CCC"]
In [3]: list(product(string_left, string_right))
Out[3]: [('AAA', 1), ('AAA', 2), ('BBB', 1), ('BBB', 2), ('CCC', 1), ('CCC', 2)]
Also if we use this approach, we don't need to convert the range into a list, since itertools.product takes iterators as an input
from itertools import product
string_right = range(1,100)
string_left = ['AAA','BBB', "CCC"]
#Take cartesian product of the two lists, and join elements together of each tuple
print([ '{}{}'.format(j,i) for i,j in product(string_right,string_left)])
The output will be
['AAA1', 'BBB1', 'CCC1', 'AAA2', 'BBB2', 'CCC2', 'AAA3', 'BBB3', 'CCC3', 'AAA4', 'BBB4', 'CCC4', 'AAA5', 'BBB5', 'CCC5', 'AAA6', 'BBB6', 'CCC6', 'AAA7', 'BBB7', 'CCC7', 'AAA8', 'BBB8', 'CCC8', 'AAA9', 'BBB9', 'CCC9', 'AAA10', 'BBB10', 'CCC10', 'AAA11', 'BBB11', 'CCC11', 'AAA12', 'BBB12', 'CCC12', 'AAA13', 'BBB13', 'CCC13', 'AAA14', 'BBB14', 'CCC14', 'AAA15', 'BBB15', 'CCC15', 'AAA16', 'BBB16', 'CCC16', 'AAA17', 'BBB17', 'CCC17', 'AAA18', 'BBB18', 'CCC18', 'AAA19', 'BBB19', 'CCC19', 'AAA20', 'BBB20', 'CCC20', 'AAA21', 'BBB21', 'CCC21', 'AAA22', 'BBB22', 'CCC22', 'AAA23', 'BBB23', 'CCC23', 'AAA24', 'BBB24', 'CCC24', 'AAA25', 'BBB25', 'CCC25', 'AAA26', 'BBB26', 'CCC26', 'AAA27', 'BBB27', 'CCC27', 'AAA28', 'BBB28', 'CCC28', 'AAA29', 'BBB29', 'CCC29', 'AAA30', 'BBB30', 'CCC30', 'AAA31', 'BBB31', 'CCC31', 'AAA32', 'BBB32', 'CCC32', 'AAA33', 'BBB33', 'CCC33', 'AAA34', 'BBB34', 'CCC34', 'AAA35', 'BBB35', 'CCC35', 'AAA36', 'BBB36', 'CCC36', 'AAA37', 'BBB37', 'CCC37', 'AAA38', 'BBB38', 'CCC38', 'AAA39', 'BBB39', 'CCC39', 'AAA40', 'BBB40', 'CCC40', 'AAA41', 'BBB41', 'CCC41', 'AAA42', 'BBB42', 'CCC42', 'AAA43', 'BBB43', 'CCC43', 'AAA44', 'BBB44', 'CCC44', 'AAA45', 'BBB45', 'CCC45', 'AAA46', 'BBB46', 'CCC46', 'AAA47', 'BBB47', 'CCC47', 'AAA48', 'BBB48', 'CCC48', 'AAA49', 'BBB49', 'CCC49', 'AAA50', 'BBB50', 'CCC50', 'AAA51', 'BBB51', 'CCC51', 'AAA52', 'BBB52', 'CCC52', 'AAA53', 'BBB53', 'CCC53', 'AAA54', 'BBB54', 'CCC54', 'AAA55', 'BBB55', 'CCC55', 'AAA56', 'BBB56', 'CCC56', 'AAA57', 'BBB57', 'CCC57', 'AAA58', 'BBB58', 'CCC58', 'AAA59', 'BBB59', 'CCC59', 'AAA60', 'BBB60', 'CCC60', 'AAA61', 'BBB61', 'CCC61', 'AAA62', 'BBB62', 'CCC62', 'AAA63', 'BBB63', 'CCC63', 'AAA64', 'BBB64', 'CCC64', 'AAA65', 'BBB65', 'CCC65', 'AAA66', 'BBB66', 'CCC66', 'AAA67', 'BBB67', 'CCC67', 'AAA68', 'BBB68', 'CCC68', 'AAA69', 'BBB69', 'CCC69', 'AAA70', 'BBB70', 'CCC70', 'AAA71', 'BBB71', 'CCC71', 'AAA72', 'BBB72', 'CCC72', 'AAA73', 'BBB73', 'CCC73', 'AAA74', 'BBB74', 'CCC74', 'AAA75', 'BBB75', 'CCC75', 'AAA76', 'BBB76', 'CCC76', 'AAA77', 'BBB77', 'CCC77', 'AAA78', 'BBB78', 'CCC78', 'AAA79', 'BBB79', 'CCC79', 'AAA80', 'BBB80', 'CCC80', 'AAA81', 'BBB81', 'CCC81', 'AAA82', 'BBB82', 'CCC82', 'AAA83', 'BBB83', 'CCC83', 'AAA84', 'BBB84', 'CCC84', 'AAA85', 'BBB85', 'CCC85', 'AAA86', 'BBB86', 'CCC86', 'AAA87', 'BBB87', 'CCC87', 'AAA88', 'BBB88', 'CCC88', 'AAA89', 'BBB89', 'CCC89', 'AAA90', 'BBB90', 'CCC90', 'AAA91', 'BBB91', 'CCC91', 'AAA92', 'BBB92', 'CCC92', 'AAA93', 'BBB93', 'CCC93', 'AAA94', 'BBB94', 'CCC94', 'AAA95', 'BBB95', 'CCC95', 'AAA96', 'BBB96', 'CCC96', 'AAA97', 'BBB97', 'CCC97', 'AAA98', 'BBB98', 'CCC98', 'AAA99', 'BBB99', 'CCC99']
This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 5 years ago.
I have 2 lists of the same size.
list1 = [start1,start2,start3, start4]
list2 = [end1, end2, end3, end4]
startn in list1 corresponds to endn in list2.
I want to use both the lists in a single for loop for further calculations.
Problem being: I want to use a combination of 2 elements from each list in the for loop. For example:
I want to extract start1, start3 from list1 and end1, end3 from list2 and use these 4 values in a for loop.
For a single list, to extract a combination of 2 elements, I know it's the following code:
import itertools
for a, b in itertools.combinations(mylist, 2):
But how do I extract 2 values from list1 and the same corresponding values from list2 and use in a for loop?
You can zip the two lists and then use combination to pull out the values:
list1 = ['a', 'b', 'c', 'd']
list2 = [1,2,3,4]
from itertools import combinations
for x1, x2 in combinations(zip(list1, list2), 2):
print(x1, x2)
#(('a', 1), ('b', 2))
#(('a', 1), ('c', 3))
#(('a', 1), ('d', 4))
#(('b', 2), ('c', 3))
#(('b', 2), ('d', 4))
#(('c', 3), ('d', 4))
Use zip to combine the start and end lists together into a bunch of tuples: (s1, e1), (s2, e2), etc. Then do combinations of that:
import itertools
starts = 'start1 start2 start3 start4'.split()
ends = 'end1 end2 end3 end4'.split()
se_pairs = zip(starts, ends)
for a,b in itertools.combinations(se_pairs, 2):
a_start, a_end = a
b_start, b_end = b
print("a: (", a_start, ",", a_end, ")", "b: (", b_start, ",", b_end, ")")
There's probably a more Pythonic way but try this:
from itertools import combinations
for i, j in combinations(range(4), 2):
list1_1, list1_2, list2_1, list2_2 = list1[i], list1[j], list2[i], list2[j]
Edit: on second thoughts this is the Pythonic way. I see other people have the same idea though.
for (list1_1, list1_2), (list2_1, list2_2) in combinations(zip(list1, list2), 2):
I am using Python 3 and I want to write a function that takes a string of all capital letters, so suppose s = 'VENEER', and gives me the following output '614235'.
The function I have so far is:
def key2(s):
new=''
for ch in s:
acc=0
for temp in s:
if temp<=ch:
acc+=1
new+=str(acc)
return(new)
If s == 'VENEER' then new == '634335'. If s contains no duplicates, the code works perfectly.
I am stuck on how to edit the code to get the output stated in the beginning.
Note that the built-in method for replacing characters within a string, str.replace, takes a third argument; count. You can use this to your advantage, replacing only the first appearance of each letter (obviously once you replace the first 'E', the second one will become the first appearance, and so on):
def process(s):
for i, c in enumerate(sorted(s), 1):
## print s # uncomment to see process
s = s.replace(c, str(i), 1)
return s
I have used the built-in functions sorted and enumerate to get the appropriate numbers to replace the characters:
1 2 3 4 5 6 # 'enumerate' from 1 -> 'i'
E E E N R V # 'sorted' input 's' -> 'c'
Example usage:
>>> process("VENEER")
'614235'
One way would be to use numpy.argsort to find the order, then find the ranks, and join them:
>>> s = 'VENEER'
>>> order = np.argsort(list(s))
>>> rank = np.argsort(order) + 1
>>> ''.join(map(str, rank))
'614235'
You can use a regex:
import re
s="VENEER"
for n, c in enumerate(sorted(s), 1):
s=re.sub('%c' % c, '%i' % n, s, count=1)
print s
# 614235
You can also use several nested generators:
def indexes(seq):
for v, i in sorted((v, i) for (i, v) in enumerate(seq)):
yield i
print ''.join('%i' % (e+1) for e in indexes(indexes(s)))
# 614235
From your title, you may want to do like this?
>>> from collections import OrderedDict
>>> s='VENEER'
>>> d = {k: n for n, k in enumerate(OrderedDict.fromkeys(sorted(s)), 1)}
>>> "".join(map(lambda k: str(d[k]), s))
'412113'
As #jonrsharpe commented I didn't need to use OrderedDict.
def caps_to_nums(in_string):
indexed_replaced_string = [(idx, val) for val, (idx, ch) in enumerate(sorted(enumerate(in_string), key=lambda x: x[1]), 1)]
return ''.join(map(lambda x: str(x[1]), sorted(indexed_replaced_string)))
First we run enumerate to be able to save the natural sort order
enumerate("VENEER") -> [(0, 'V'), (1, 'E'), (2, 'N'), (3, 'E'), (4, 'E'), (5, 'R')]
# this gives us somewhere to RETURN to later.
Then we sort that according to its second element, which is alphabetical, and run enumerate again with a start value of 1 to get the replacement value. We throw away the alpha value, since it's not needed anymore.
[(idx, val) for val, (idx, ch) in enumerate(sorted([(0, 'V'), (1, 'E'), ...], key = lambda x: x[1]), start=1)]
# [(1, 1), (3, 2), (4, 3), (2, 4), (5, 5), (0, 6)]
Then map the second element (our value) sorting by the first element (the original index)
map(lambda x: str(x[1]), sorted(replacement_values)
and str.join it
''.join(that_mapping)
Ta-da!
I have a list containing tuples that is generated from a database query and it looks something like this.
[(item1, value1), (item2, value2), (item3, value3),...]
The tuple will be mixed length and when I print the output it will look like this.
item1=value1, item2=value2, item3=value3,...
I have looked for a while to try to find a solution and none of the .join() solutions I have found work for this type of situation.
You're after something like:
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>> ', '.join('{}={}'.format(*el) for el in a)
'val=1, val2=2, val3=3'
This also doesn't care what type the tuple elements are... you'll get the str representation of them automatically.
You can use itertools as well
from itertools import starmap
', '.join(starmap('{}={}'.format, a))
If each tuple is only an (item, value) pair then this should work:
l = [(item1, value1), (item2, value2), (item3, value3), ...]
', '.join('='.join(t) for t in l)
'item1=value1, item2=value2, item3=value3, ...'
Try this:
lst = [('item1', 'value1'), ('item2', 'value2'), ('item3', 'value3')]
print ', '.join(str(x) + '=' + str(y) for x, y in lst)
I'm explicitly converting to string the items and values, if one (or both) are already strings you can remove the corresponding str() conversion:
print ', '.join(x + '=' + y for x, y in lst)
One possible solution is this, definitely the shortest code
>>> a = [('val', 1), ('val2', 2), ('val3', 3)]
>>>', '.join('%s=%s' % v for v in a)
'val=1, val2=2, val3=3'
works with python 2.7 as well
If you want something like that, I would use a dictionary.
dict = {1:2,3:4}
print dict
Then, you can loop through it like this:
dict = {1:2,3:3}
print dict
for i in dict:
print i, "=", dict[i]
Hope it helps!