Python-Repeat List 2 with each argument in List 1 without duplication

Asked 1 years ago, Updated 1 years ago, 145 views

How do I simplify the code below?

Newlist =[ ]

A_list = [a, b, c, d, e, f]

page_list = [1, 4, 5]

''''''''''''''''''

for 'A' in A_list:

names1 = Class Method Function (type='A', page=1)

Newlist.extend(names1)

names2 = Class Method Function (type='A', page=4)

Newlist.extend(names2)

names3 = Class Method Function (type='A', page=5)

Newlist.extend(names3)

The page value is a list, but I don't know how to combine it with A_list as a for statement. The result you want is (a, 1) (a, 4) (a, 5) (b, 1) (b, 4) (b, 5) . . .

python loops for

2022-09-22 19:23

2 Answers

Try the itertools module for repetitive tasks.

import itertools

A_list = ['a', 'b', 'c', 'd', 'e', 'f']
page_list = [1, 4, 5]
list(itertools.product(A_list, page_list))

[('a', 1),
 ('a', 4),
 ('a', 5),
 ('b', 1),
 ('b', 4),
 ('b', 5),
 ('c', 1),
 ('c', 4),
 ('c', 5),
 ('d', 1),
 ('d', 4),
 ('d', 5),
 ('e', 1),
 ('e', 4),
 ('e', 5),
 ('f', 1),
 ('f', 4),
 ('f', 5)]


2022-09-22 19:23

Newlist =[ ]

A_list = ['a', 'b', 'c', 'd', 'e', 'f']

page_list = [1, 4, 5]

for i in A_list : for v in page_list : Newlist.append((i,v))


2022-09-22 19:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.