Reputation: 802
What would be the most pythonic way of achieving the following:
list_a = ["A", "B", "C"]
list_b = ["X", "Y", "Z"]
idx_start = 100
result = [ (100, "A", "X"), (101, "B", "Y"), (102, "C", "Z") ]
The lists are guaranteed to be of the same size.
Upvotes: 3
Views: 739
Reputation: 5289
Since you accepted that your result can be a dictionary (or list) with tuples for values, try this:
>>> list_a = ['A', 'B', 'C']
>>> list_b = ['X', 'Y', 'Z']
>>> idx_start = 100
>>>
>>> result_list = list(enumerate(zip(list_a, list_b), start=idx_start))
>>> result_dict = dict(enumerate(zip(list_a, list_b), start=idx_start))
>>>
>>> print (result_list)
[(100, ('A', 'X')), (101, ('B', 'Y')), (102, ('C', 'Z'))]
>>> print (result_dict)
{100: ('A', 'X'), 101: ('B', 'Y'), 102: ('C', 'Z')}
Upvotes: 0
Reputation: 16711
Use a list comprehension:
[(i + start, a, b) for i, (a, b) in enumerate(zip(list_a, list_b))]
Upvotes: 1
Reputation: 33
I had the same issue using HashSet. What I did was instantiate a var inside a for loop adding index and both values inside the HashSet. Something logic like that:
for (int i=0; i<a.length(); i++) {
result.add(i,list_a[i],list_b[i]);
}
Upvotes: 0
Reputation: 23144
from itertools import count
zip(count(idx_start), list_a, list_b)
Upvotes: 3
Reputation: 1021
Zip is also an option
zip(range(idx_start,idx_start+len(list_a)), list_a, list_b)
Upvotes: 2
Reputation: 52071
You can try a list comp
>>> list_a = ["A", "B", "C"]
>>> list_b = ["X", "Y", "Z"]
>>> idx_start = 100
>>> [(idx_start+i,list_a[i],list_b[i]) for i in range(len(list_a))]
[(100, 'A', 'X'), (101, 'B', 'Y'), (102, 'C', 'Z')]
Other ways include
[(idx_start+i,list_a[i],list_b[i]) for i,v in enumerate(list_a)]
Upvotes: 3