Home > front end >  Iterate through multiple lists and a conditional if-statement
Iterate through multiple lists and a conditional if-statement

Time:11-05

I want to iterate through 3 lists where the first list is conditional (1 or 0) if list1 == 1: print('Some text', item0 in list2, 'Some text' item0 in list2, 'some text', item0 in list3)

This is my code

dicts = {0:1, 1:1, 2:1}
values = list(dicts.values()) #Makin a list from values in my dict (1 or 0) my new list now contains [1, 1, 1]

cells = ['ABC', 'DEF', 'GHI']
nodes = ['123', '456', '789']

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

I want the result to end up with:

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

I've tried multiple approches but i cant seem to get it right

CodePudding user response:

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

CodePudding user response:

Replace your print statement by this

print('Some Text ', c,'Some Text ', c, ' text', n,  'Some Text')
  • Related