How to Iterate Through Two Lists in Parallel

How do I iterate through two lists in parallel?

Python 3

for f, b in zip(foo, bar):
print(f, b)

zip stops when the shorter of foo or bar stops.

In Python 3, zip
returns an iterator of tuples, like itertools.izip in Python2. To get a list
of tuples, use list(zip(foo, bar)). And to zip until both iterators are
exhausted, you would use
itertools.zip_longest.

Python 2

In Python 2, zip
returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive
temporary variable, and should be replaced by itertools.izip or
itertools.izip_longest, which returns an iterator instead of a list.

import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)

izip stops when either foo or bar is exhausted.
izip_longest stops when both foo and bar are exhausted.
When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.


Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))

prints

1 red manchego
2 blue stilton
3 green brie

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

This is as pythonic as you can get:

for lat, long in zip(Latitudes, Longitudes):
print(lat, long)

For loop iterating through two lists python

i assume that you have the same list length for list1 and list 2

in order to print it you just need to specify the position of the index on list like list[index], this will print the list value.

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]

for i in range(len(list1)):
print(f"{list1[i]}, {list2[i]}")

How to iterate two list in parallel in Kotlin?

Try to zip two lists:

fun main() {
val list1 = listOf(1,2,3)
val list2 = listOf(4,5,6)
list1.zip(list2).forEach {pair ->
println(pair.component1() + pair.component2())
}
}

This prints:

5
7
9

In your case given the allArea list and allTextViews have the same length, you can zip them and get the pair of which the first component will be of type Double, and the second is of type TextView

Efficient way to iterate over two related ArrayLists?

The Answer by dreamcrash is correct: While your looping of a pair of arrays works, you should instead take advantage of Java as a OOP language by defining your own class.

Record

Defining such a class is even simpler in Java 16 with the new records feature. Write your class as a record when it’s main purpose is communicating data, transparently and immutably.

A record is very brief by default. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString. You need only declare the type and name of each member field.

record ColorNoun ( String color , String noun ) {}

Use a record like a conventional class. Instantiate with new.

ColorNoun blueSky = new ColorNoun ( "Blue" , "Sky" ) ;

Note that a record can be declared locally within a method, or declared separately like a conventional class.

How to loop through two list of lists at once and replace values from one list with the other list?

Assuming the names in a are unique, you could create a dict from a to avoid looping through it over and over as you replace the empty string values in b. For example (added a couple items to your examples to illustrate what would happen if a name in b does not exist in a):

a = [['Dany', '021'], ['Alex','035'], ['Joe', '054']]
b = [['Alex',''], ['Dany', ''], ['Jane', '']]

d = {k: v for k, v in a}
b = [[k, d[k]] if k in d else [k, v] for k, v in b]
print(b)
# [['Alex', '035'], ['Dany', '021'], ['Jane', '']]

If the list you are actually working with is just a simple list of pairs as in the example, then you could replace the dict comprehension above with dict(a).

Also, in case it is not clear, the various k, v references are for convenience in unpacking the nested pairs, but you could just use a single variable and access using index values like:

{x[0]: x[1] for x in a}

How to iterate over two arrays in parallel?

To iterate over multiple list you can use the built in function zip. According to the Documentation, this function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. So, applied to your particular example

list1 = [ 'one', 'two', 'three' ]
list2 = [ 'I', 'II', 'III', 'IV', 'V' ]

for word in list1:
print word + " from list1"

for roman in list2:
print roman + " from list2"

for word, roman in zip(list1, list2):
print word + " from list1"
print roman + " from list2"

The only drawback of zip is that when your lists, as in this example, have not equal length, zip will return a list of tuples, each with dimension equal to the smaller one. To favour the longest one, and fill with None when necessary, just replace zip with itertools.izip_longest:

from itertools import izip_longest

list1 = [ 'one', 'two', 'three' ]
list2 = [ 'I', 'II', 'III', 'IV', 'V' ]

for word in list1:
print word + " from list1"

for roman in list2:
print roman + " from list2"

for word, roman in izip_longest(list1, list2):
print word + " from list1"
print roman + " from list2"

Looping through two lists in parallel

If I understand correctly, time would be set on a quarterly basis and you would like to get the sum of X for each time. Next time, consider giving the expected output in your question.

data stage1;
do time=3 to 12 by 3;
do value = 0.03, 0.04, 0.05, 0.06;
x=(2/value)*time;
output;
end;
end;
run;

proc sort data=stage1;
by time value;
run;

data want;
do _n_=1 by 1 until(last.time);
set stage1;
by time;
sum_x=sum(sum_x, x);
output;
end;
run;
time  value x  sum_x
3 0.03 200 200
3 0.04 150 350
3 0.05 120 470
3 0.06 100 570
6 0.03 400 400
6 0.04 300 700
6 0.05 240 940
6 0.06 200 1140
9 0.03 600 600
9 0.04 450 1050
9 0.05 360 1410
9 0.06 300 1710
12 0.03 800 800
12 0.04 600 1400
12 0.05 480 1880
12 0.06 400 2280

EDIT after comments

Why would you use a do loop? Just perform element-wise multiplication within a table.

data want;
set have;
x=(2/value)*time;
retain sum_x 0;
sum_x=sum(sum_x, x);
output;
run;

Iterate through multiple lists and a conditional if-statement

Looks like you just inverted c and n in your loop:

for v, n, c in zip(values, nodes, cells):
if v == 1:
print('Some Text', n, ' Some Text', n, 'text', c, 'Some Text')

NB. you don't need to add spaces around the chunks if using print with many parameters

output:

Some Text 123 Some Text 123 text ABC Some Text
Some Text 456 Some Text 456 text DEF Some Text
Some Text 789 Some Text 789 text GHI Some Text


Related Topics



Leave a reply



Submit