user1655380
user1655380

Reputation: 71

Printing Multiple Lists using Format

I am having 2 lists with variable sizes that need to be printed alongside each each other. For instance, if

A = [30, 40, 50]
B = [1,2,3]

Then, I want to print an output that looks like:

A 30 B 1 A 40 B 2 A 50 B 3

I have tried something similar to

print (len(A)* ('A {} B {}').format(*A,*B) 

but this does not give me what I am looking for.

Any help would be appreciated.

Upvotes: 1

Views: 343

Answers (3)

Dmytro Chasovskyi
Dmytro Chasovskyi

Reputation: 3631

One of the possible solution:

print(*map(lambda x, y: "A {} B {}".format(x, y), A, B))

lambda x, y - lambda function takes 2 arguments (each element from A and B) and create a data structure called map (similar to list). After this, we treat map-like data structure as a regular list and print each specific element.

Input

A = [1, 2, 3]
B = [4, 5, 6]

Intermediate result

For explanation purpose, exclusively.

print(*map(["A 1 B 4", "A 2 B 5", "A 3 B 6"]))

Output

A 1 B 4 A 2 B 5 A 3 B 6

In case when one of the arrays will be shorter, it will return the following:

Input

A = [1, 2]
B = [4, 5, 6]

Output

A 1 B 4 A 2 B 5

For more details, take a look on map.

Inspired by Q&A

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could zip both lists:

A = [30, 40, 50]
B = [1,2,3]

result = ' '.join('A {} B {}'.format(a, b) for a, b in zip(A, B))
print(result)

Output

A 30 B 1 A 40 B 2 A 50 B 3

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Using a simple iteration with enumerate

Ex:

A = [30, 40, 50]
B = [1,2,3]

print(" ".join("A {} B {}".format(v, B[i]) for i,v in enumerate(A)))

Output:

A 30 B 1 A 40 B 2 A 50 B 3

Upvotes: 1

Related Questions